- Home /
Prefab attached to script is destroying itself before Instantiate() is called
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?
Answer by ifurkend · Mar 22, 2018 at 03:14 AM
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.
The problem is is that I'm setting the public GameObject variable to the prefab, and the prefab's script is running before the GameObject is being instantiated. Does that make sense? I try instantiating the prefab but it comes back saying it's null because its already destroyed itself.
You need to share your full code to get help. Right now we have very vague idea how you instantiate your particle system.