2
votes

I currently have a script that should Instantiate a particle system and destroy it after a certain amount of time, but after the object is Instantiated, this error code shows up:

MissingReferenceException: The object of type 'ParticleSystem' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

the script is currently goes as such:

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);
    }
}

How can i Instantiate this particle system and destroy it properly?

1

1 Answers

6
votes

You are attempting to destroy the prefab ParticleSystem which the smoke variable not the ParticleSystem you instantiated.

The Instantiate function returns any GameObject it instantiates. To destroy the ParticleSystem you just instantiated, you have to instantiate it, store it in a temporary variable then destroy it with that temporary variable later on.

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