Destroy()在Unity3D中不再工作

本文关键字:不再 工作 Unity3D Destroy | 更新日期: 2023-09-27 18:25:09

我正在开发一款赛车游戏,它在地面上有加速器。当车辆接触到它时,附在速度助推器上的脚本会实例化一个Fire预制件,然后在2秒钟后将其摧毁。

这是我的脚本(在C#中),它过去工作得很好,但现在Destroy()函数没有任何效果,我可以在游戏层次结构中看到我的Fire预制实例:

private GameObject _fireModel, _fireObj;
void Start ()
{
    _fireModel = Resources.Load("Fire1") as GameObject;
    _watch = new Stopwatch();
    enabled = false; // (don't call Update() on each frame)
}
void OnTriggerEnter (Collider col)
{
    _fireObj = Instantiate(_fireModel) as GameObject;
    enabled = true; // (do call Update() on each frame)
    _watch.Start();
}
void Update ()
{
    _fireObj.transform.position = _player.position;
    if (_watch.ElapsedMilliseconds >= _fireDurationMs)
    {
        Destroy(_fireObj);
        _watch.Stop();
        _watch.Reset();
        enabled = false; // if I remove this line, 
        // I get a console error saying _fireObj 
        // has been destroyed! Yet I can still 
        // see it on the game and in the hierarchy
    }
}

你看到这个脚本不会破坏Fire1实例的情况吗?

Destroy()在Unity3D中不再工作

如果_fireDurationMs内发生两个OnTriggerEnter事件,则将获得两个新的对象实例化,并且只有1个实例将被销毁,因为您只保留了对最新火的引用。

如果这是我的游戏,我会改进一下设计。你可以制作一个名为"DestroyAfterMilliseconds"的脚本,在预设的时间发生后摧毁它所连接的游戏对象,并将其连接到火预制板上,而不是让速度助推器负责摧毁火。然后,每一次火灾都要负责摧毁自己,而助推器的责任就会减少。然后,同一个脚本可以在任何其他对象上重复使用,您希望给这些对象有限的生存期。拆分职责也会使代码更容易调试和维护。

您只需要为fire对象添加一个脚本。

using UnityEngine;
using System.Collections;
public class fireScript: MonoBehaviour {

    void Start () {
        Destroy(gameObject, 2f);
    }

    void Update () {
    }
}
`  

现在,您不必在另一个脚本中控制您的火对象。只要初始化它,Firescript就会处理destroy方法。

这对我有效。

 Destroy(RigidbodyVariable);//First Line for Rigidbody
 Destroy(GameObjectVariable);//Second Line GameObject