OnEnable不更新变量-Unity3D

问题描述

我有一群敌人跟随玩家在游戏中被激活/停用。 问题在于,一旦它们被重新激活,它们将保留它们在被停用之前所具有的苯乙烯刚度。速度值,并且不会像我在OnEnable()函数中所写的那样更新它们,因此它们只是移到其他位置而不是跟随播放器。 我的代码如下:

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;
    }

我确定我犯了一个新手错误,但是我无法弄清楚。 谢谢您的关注。

解决方法

您正在使用OnEnable,但没有使用OnDisable,请尝试在OnDisable内设置刚体属性重置。

还请记住,OnEnable将在Start之前执行。

有关执行顺序here的更多信息。