我试着做一个射击游戏,我想为子弹设置一个靶场。这意味着,当它被击中时,它会飞行一段时间,然后被摧毁。
我尝试过Destroy函数;但是,我实现代码的方式似乎是试图从发射点而不是在其范围的末尾销毁原始子弹。
,这是我的代码:
if (Input.GetKey("space"))
{
Instantiate(bullet, transform.position + new Vector3(0, 0, 1), bullet.rotation);
Destroy(bullet, 0.4f);
}一旦我得到MissingReferenceException,它就会开火。
发布于 2019-06-18 09:30:21
你毁了预制件。当您实例化时,您将得到一个引用,这是您想要销毁的实际游戏对象。
if (Input.GetKey("space"))
{
GameObject bulletInstance; //or whatever type your bullet is
bulletInstance = Instantiate(bullet, transform.position + new Vector3(0, 0, 1), bullett.rotation);
Destroy(bulletInstance , 0.4f); //if you instantiated via a component, you have to destroy bulletInstance.gameObject or you'll only destroy the component
}https://docs.unity3d.com/Manual/InstantiatingPrefabs.html
编辑:请注意,这会造成大量的垃圾,而且只是为了回答您的问题,您应该考虑使用对象池来获取符号。https://learn.unity.com/tutorial/object-pooling
https://stackoverflow.com/questions/56645807
复制相似问题