If your main goal is to prevent the odd enemy movement, a simple solution could be to check in the OnTriggerExit2D whether the trigger belongs to the player or not, regardless of whether the player is alive:
void OnTriggerExit2D(Collider2D other)
{
if(other.gameObject.GetComponent<PlayerMovement>())
{
return; // Don't do anything further when colliding with the player
}
moveSpeed = -moveSpeed;
FlipEnemyFacing();
}
Specifically to get access to the isAlive
bool, you’ll need to either make it public instead of private or create a method to check the value. You can put this in PlayerMovement
:
public bool IsAlive()
{
return isAlive;
}
Then a similar check to the one above, but specifically accessing that method:
void OnTriggerExit2D(Collider2D other)
{
if(other.gameObject.GetComponent<PlayerMovement>())
{
if(!other.gameObject.GetComponent<PlayerMovement>().IsAlive())
{
return; // Don't do anything further when colliding with the dead player
}
}
moveSpeed = -moveSpeed;
FlipEnemyFacing();
}
The first if
checks that there is a PlayerMovement
component because without one we can’t then try to check for something specific.
There are more complicated ways to do these things as well, but either of these approaches should give you the desired result.