I have a pool of enemies that follow the player being activated/deactivated during the game. The problem is once they are reactivated, they retain the rigidbody.velocity values they had before being deactivated and don't update them as I wrote on the OnEnable() function, so they just go somewhere else instead of following the player. My code is as follows:
public class EnemyFollow : MonoBehaviour
{
public GameObject playerPos;
protected Rigidbody rb;
bool secondSpawn = false;
private void OnEnable()
{
if (secondSpawn)
{
Vector3 dir = new Vector3(playerPos.transform.position.x - transform.position.x,
playerPos.transform.position.y - transform.position.y,
playerPos.transform.position.z - transform.position.z).normalized;
rb.velocity = dir;
}
}
void Start()
{
playerPos = GameObject.FindGameObjectWithTag("Player");
rb = GetComponent<Rigidbody>();
Vector3 dir = (playerPos.transform.position - transform.position).normalized;
rb.velocity = dir;
secondSpawn = true;
}
I'm sure I'm making a noob mistake, but I just can't figure it out. Thank you for your attention.
You're using
OnEnable
, but noOnDisable
, try to set your rigidbody properties reset inside OnDisable.Also remember that
OnEnable
will be executed beforeStart
.More about execution order here.