OnEnable not updating variables - Unity3D

512 Views Asked by At

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.

1

There are 1 best solutions below

2
On

You're using OnEnable, but no OnDisable, try to set your rigidbody properties reset inside OnDisable.

Also remember that OnEnable will be executed before Start.

More about execution order here.