实例化并销毁GameObject/ParticleSystem

Jus*_*era 0 c# unity-game-engine

我目前有一个脚本应该实例化粒子系统并在一段时间后销毁它,但在实例化对象后,此错误代码显示:

MissingReferenceException:'ParticleSystem'类型的对象已被销毁,但您仍在尝试访问它.您的脚本应该检查它是否为null或者您不应该销毁该对象.

该脚本目前是这样的:

public class MuzzleFlash : MonoBehaviour {

    public Transform gun;
    public ParticleSystem smoke;
    public ParticleSystem flare;
    public ParticleSystem bullet;
    private float smokeTime = 0.2f;

    private void Update () {
        if (Input.GetButtonDown("Fire1"))
        {
            smokeFun();
            flare.Play();
            bullet.Play();
        }
    }

    void smokeFun()
    {
        Instantiate(smoke, gun);
        Destroy(smoke, smokeTime);
    }
}
Run Code Online (Sandbox Code Playgroud)

}

我如何实例化这个粒子系统并正确销毁它?

Pro*_*mer 6

您试图销毁预变量,而预变量不是 您实例化ParticleSystemsmoke变量ParticleSystem.

Instantiate函数返回它实例化的任何GameObject.要销毁ParticleSystem刚刚实例化的对象,必须将其实例化,将其存储在临时变量中,然后使用该临时变量将其销毁.

void smokeFun()
{
    //Instantiate and store in a temporary variable
    ParticleSystem smokeInstance = Instantiate(smoke, gun);
    //Destroy the Instantiated ParticleSystem 
    Destroy(smokeInstance, smokeTime);
}
Run Code Online (Sandbox Code Playgroud)