我正在使用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);
}
}
我希望GameObject“ BumperPrefab”出现,并停留0.2秒并消失。我应该能够重复多次,但是实际上发生的是,我只能执行一次,然后出现错误“ GameObject类型的对象已被破坏,但您仍在尝试访问它”出现,我无法再次显示BumperPrefab。
非常感谢您的帮助!
答案 0 :(得分: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);
}
现在,您要用实例化的对象覆盖包含预制对象的公共字段,然后销毁它。将实例化的对象设置为变量,就可以了。
答案 1 :(得分:0)
问题是,在您的代码中,您并不关心GameObject是否存在。因此,例如,如果(由于某种原因)将不创建对象BumperPrefab,则Destory()将尝试对null进行操作。 您可以尝试通过以下方式将其添加到BumperPrefab脚本bomber.cs中:
float lifetime = 0.2f;
private void OnEnable()
{
Desroy(this, lifetime)
}
答案 2 :(得分:0)
问题是您要销毁BumperPrefab
Instantiate
新GameObject
时,应将其添加到这样的本地变量中
var newbumper = (GameObject) Instantiate(BumperPrefab, firePoint.position,firePoint.rotation);
,并且您必须销毁包含新创建的gameObject
Destroy(newbumper , lifetime);