I have a particle system GameObject that has a script on it to destroy itself when the particle system is finished playing:
void Update () {
if (!GetComponent<ParticleSystem>().IsAlive()) {
Destroy(this.gameObject);
}
}
I have another GameObject with a script with a reference to the particle system prefab:
public GameObject m_hitWallParticle;
For some reason, the prefab’s Update() script is being run without being instantiated. What’s going on here? Am I going about this the wrong way?
Not enough information, but it could be the particle effect prefab has its “play on awake” property unchecked, hence when you instantiate it the effect does not start playing instantly, subsequently IsAlive() thinks the effect is not alive. Most importantly, if you can predict the duration of your effect, then its best to avoid IsAlive() and give the delay time to Destroy() second attribute, so you can get rid of that if statement.
Other tips:
First avoid constantly GetComponent for performance’s sake, especially during Update(). Instead, do it in Awake() or OnEnable() once only and assign it to a variable.
Second, you should avoid destroying your object you are going to instantiate it in the same scene again. You can leave the inactive particle system as is. When you need it again, relocate and play it again.