Particle system destroyed when ParticleSystem.Play() is called

I have a particle system that I want to play in code. However, when I call ParticleSystem.Play(), I get a NullReferenceException saying the particle system has been destroyed but I am still trying to access it. Removing the ParticleSystem.Play() call removes the error, so I know that’s the issue. The question is, why on God’s green earth would that happen? I’m assuming it has something to do with the collision, because ParticleSystem.Play() has worked for me very recently in other contexts, such as when a button is pressed. Any help is appreciated.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerDie : MonoBehaviour
{
    public ParticleSystem blood;

    public void OnCollisionEnter2D(Collision2D collision)
    {
        blood.Play();
    }
}

Hi @ajlott ,

Have you assigned a particle system to that public field you have in your Inspector? If it’s assigned, are you sure that you’re not destroying the object where that script is assigned to? As it’s name is PlayerDie, I thought you might destroy player (just a guess.)

At least add a check there to avoid errors and do some debug log prints to see what’s exactly happening.

if (blood != null) {
    blood.Play();
}

That OnCollisionEnter(2D) doesn’t really differ that much from any other method, it’s just called by Unity when a collision occurs to that object where that script is assigned to.

Thank you for the reply. Yes, there is a particle system assigned to the public field and I am not destroying the object the script is attached to. I will eventually destroy the object, but I wanted to get the particle system to play first. Also, if I comment out the ParticleSystem.Play call, there’s no error when the collision occurs.

Thanks again for the reply!

You probably need to drag the particle system into the field in the inspector field.

In my case the problem was a particular script associated with the explosion I was using. I was using a freely available explosion that came with a script that destroyed the particle system when it was done.

1 Like

Please don’t necro threads like this. Also, the 2D forum isn’t actually about particles.