so in my game i have lots of enemys with different death particles that die on collision. i want to make one script for them all. it would be great if this made it so i could just drag the particles i want for the object to create when it dies from the editior
here is my code so far
using UnityEngine;
public class death : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
Destroy(gameObject);
//instantiate(particle);
}
}
Seems alright to me. Declare a public ParticleSystem just above, drag in your particle system and you’re good to go. Although instead of making a prefab every time, I recommend parenting your system to your enemy prefab, disabling it and then enabling it when needed, delaying the destruction by your system’s duration (delay is built into the Destroy method).
Or in code:
public class death : MonoBehaviour {
public ParticleSystem deathParticles;
private void OnCollisionEnter2D(Collision2D collision)
{
Destroy (gameObject, deathParticles.duration);
deathParticles.SetActive (true);
}
}
If you’re doing large numbers of enemies, though, I recommend you look into object pooling. Creating and destroying takes lots of memory.