如何修复 Unity 中的 "the object of type 'GameObject' has been destroyed, but you are still trying to access it" 错误?

How to fix "the object of type 'GameObject' has been destroyed, but you are still trying to access it" error in Unity?

我正在使用 C# 在 Unity 中创建 2.5D 格斗游戏。目前,我正在尝试让播放器周围出现一个保险杠,并在一定时间后消失。我设法使保险杠出现和消失一次,但在那之后,当我尝试使保险杠再次出现时,Unity 对我有一个错误:"The object of type 'GameObject' has been destroyed but you are still trying to access it."

我已经尝试使用 "instantiate" 和 "destroy" 命令,遵循 "Brackeys" 的 2D 拍摄教程。在论坛上也关注了一些关于同一问题的问题后,我再次更改了我的代码,但问题仍然存在。

firePoint 是一个空对象,BumperPrefab 从这里实例化。

using UnityEngine;

public class weapon: MonoBehaviour
{
    public Transform firePoint;
    public GameObject BumperPrefab;
    public float lifetime = 0.2f;

void Update()
{
    if (Input.GetButtonDown("Fire1"))
    {
        attack();
    }

}
void attack()
{
    BumperPrefab = (GameObject) Instantiate(BumperPrefab, firePoint.position, firePoint.rotation);
    Destroy(BumperPrefab, lifetime);
}

}

我希望游戏对象 "BumperPrefab" 出现,停留 0.2 秒然后消失。我应该可以根据需要重复多次,但实际发生的是我只能执行一次,然后出现错误 "The object of type 'GameObject' has been destroyed but you are still trying to access it",我无法再次出现 BumperPrefab。

非常感谢任何帮助!

using UnityEngine;

public class weapon: MonoBehaviour
{
    public Transform firePoint;
    public GameObject BumperPrefab;
    public float lifetime = 0.2f;

void Update()
{
    if (Input.GetButtonDown("Fire1"))
    {
        attack();
    }

}
void attack()
{
    var bumper = (GameObject) Instantiate(BumperPrefab, firePoint.position, firePoint.rotation);
    Destroy(bumper, lifetime);
}

现在您正在用您的实例化对象覆盖包含预制对象的 public 字段,然后销毁它。将实例化对象设置为变量,应该没问题。

问题是在您的代码中您不关心您的 GameObject 是否存在。因此,例如,如果(出于某种原因)对象 BumperPrefab 不会被创建,Destory() 将尝试对 null 进行操作。 您可以尝试使用以下方式添加到 BumperPrefab 脚本 bumper.cs:

float lifetime = 0.2f;

private void OnEnable()
{
Desroy(this, lifetime)
}

问题是你正在破坏BumperPrefab

当你 Instantiate 一个新的 GameObject 时,你应该像这样将它添加到局部变量

var newbumper = (GameObject) Instantiate(BumperPrefab, firePoint.position,firePoint.rotation);

并且您必须销毁包含新创建的局部变量 gameObject

Destroy(newbumper , lifetime);