我该如何修复 "The object of type 'GameObject' has been destroyed but you are still trying to access it"

How can I fix "The object of type 'GameObject' has been destroyed but you are still trying to access it"

我正在通过取消选中 isKinematic 创建平台坠落效果,但我不断收到错误消息: “MissingReferenceException:'GameObject' 类型的对象已被销毁,但您仍在尝试访问它。 这是我的代码:

// Update is called once per frame
void Update()
{
    
}

private void OnCollisionExit(Collision collision){
    if(collision.gameObject.tag == "Player")
    {
        Fall();
        Invoke("Fall", 0.2f); //delay 0.2 s chu y dau va viet thuong
    }
}

void Fall(){
    GetComponent<Rigidbody>().isKinematic = false;
    Destroy(gameObject,1f);

}

} Here is the error in unity

有谁知道如何解决这个问题吗?谢谢。

您当前的代码流程如下:

  • 调用了 Fall() 一次(调用 1 秒后游戏对象将被销毁)。
  • 您正在使用 Invoke 在 0.2 秒 后调用 Fall(),而您已经有一个任务从第一个开始销毁游戏对象打电话。

更新: 我假设您想立即 设置运动学错误。我更新了这段代码:)


代码

using UnityEngine;

public class Q69205071 : MonoBehaviour
{
    private void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            //Fall(1f);
            /// since you want everything to be executed after 0.2 seconds
            /// you could use Invoke or coroutines.
            Invoke("Fall", 0.2f); 
        }
    }

    private void Fall()
    {
        GetComponent<Rigidbody>().isKinematic = false;
        Destroy(gameObject, 1f); // 1 seconds delay before destroying the gameObject
    }
}

快乐编码:)