Particle System .Emit( X) not working

I am new to unity and C# so I wouldn’t be surprised if this has a simple solution, but I am struggling to play a particle system I have attached to an “Enemy” game object to be played on its death. The code I have so far is as follows:

public class Death : MonoBehaviour
{
    public ParticleSystem blood;
    
    // Start is called before the first frame update
    void Start()
    {
        blood = GetComponent<ParticleSystem>();
        Debug.Log("blood assigned");
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            blood.Emit( 100);
            Debug.Log("Playing blood");

            Destroy(this.gameObject);  
            Debug.Log("Object destroyed");
        }
    }
}

I have tried using the .Play() function as well as .Emit( X) as well as commenting out the Destroy function. The log shows all 3 debug entries so I am not sure if the .Emit() line is getting skipped over, ignored or if I have set something up incorrectly:
Screenshot 2024-08-28 133012

I think the problem here is that you have the ParticleSystem component in the same gameObject that you are destroying.
If you had another separate gameObject, it should be fine. I would use Play instead of Emit, in your case.

1 Like

There are 2 problems from what I see:

  1. The particle system is a component on the enemy object, if you call Destroy on the object it will destroy the particle system as well. To fix this you can instantiate the effect when the enemy dies (Also, you can check Pooling to improve performance with enemies and effects). A very trivial implementation would be to have the ParticleSystem on a prefab and that prefab as reference in your Death GameObject:
public class Death : MonoBehaviour
{
    public GameObject bloodPrefab;
    
  1. You should use .Play() instead of .Emit()
    You can add the logic in OnCollisionEnter:
    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            var bloodInstance = Instantiate(bloodPrefab, transform.position, transform.rotation);
            var bloodEffect = bloodInstance.GetComponent<ParticleSystem>();
            bloodEffect.Play();

            Destroy(this.gameObject);  
            Debug.Log("Object destroyed");
        }
    }

Again, this is a trivial implementation and you should definitely improve on it, like having a BloodEffect MonoBehaviour that caches the ParticleSystem and has a function Play that calls the Play on the particles, so that you don’t have to use GetComponent.

2 Likes