【问题标题】:How to fix "the object of type 'GameObject' has been destroyed, but you are still trying to access it" error in Unity?如何修复Unity中的“'GameObject'类型的对象已被破坏,但您仍在尝试访问它”错误?
【发布时间】:2019-02-08 09:15:37
【问题描述】:

我正在使用 C# 在 Unity 中创建一个 2.5D 格斗游戏。目前,我正在尝试让玩家周围出现一个保险杠,并在一段时间后消失。我已经设法让保险杠出现和消失一次,但是在那之后,当我尝试让保险杠再次出现时,Unity 对我有一个错误:“'GameObject' 类型的对象已被破坏,但你仍在尝试访问它。”

按照“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 秒然后消失。我应该可以重复多次,但实际发生的是我只能这样做一次,然后出现错误“'GameObject'类型的对象已被破坏,但您仍在尝试访问它”出现了,我无法让 BumperPrefab 再次出现。

非常感谢任何帮助!

【问题讨论】:

  • 为什么实例化的时候用(GameObject)就用var obj = Instantiate(...)然后销毁obj

标签: c# unity3d 3d 2.5d


【解决方案1】:
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);
}

现在,您正在用您的实例化对象覆盖包含预制对象的公共字段,然后将其销毁。将实例化的对象设置为变量就可以了。

【讨论】:

    【解决方案2】:

    问题是你正在破坏BumperPrefab

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

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

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

    Destroy(newbumper , lifetime);
    

    【讨论】:

      【解决方案3】:

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

      float lifetime = 0.2f;
      
      private void OnEnable()
      {
      Desroy(this, lifetime)
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-11
        • 2012-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多