My script: Only parent uses script, and checks children

I made my script back when it was first made, because I’m using different assets from the asset store, and I couldn’t figure out how to break apart the effects to use like they were being used in the lecture. So instead, I simply put the effects in as children, and had the gameObject check the children for any alive particle systems. When none are found, then it destroys the gameObject.

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

namespace RPG.Core
{
    public class DestroyAfterEffect : MonoBehaviour
    {
        private bool isAlive = false;
        void Update()
        {
            Component[] particleSystems = null;
            
            // check for children particle systems
            if(GetComponentsInChildren<ParticleSystem>() != null)
            {
                particleSystems = GetComponentsInChildren<ParticleSystem>();
            }
            // check for component particle system
            if(GetComponent<ParticleSystem>() != null)
            {
                particleSystems = particleSystems.Append(GetComponent<ParticleSystem>()).ToArray();
            }
            
            // loop through particle systems to see if any are alive
            foreach(ParticleSystem system in particleSystems)
            {
                if(system.IsAlive())
                {
                    isAlive = true;  // if they are, set isAlive to true
                }
            }
            // if isAlive remained false destroy this object
            if(isAlive == false)
            {
                Destroy(gameObject);
            } 
            else
            {
                isAlive = false;  // otherwise, reset isAlive back to false for next check
            }
        }
    }
}

This can be simplified a bit…

List<ParticleSystem> particleSystems = new List<ParticleSystem>();
void Awake()
{
     foreach(ParticleSystem system in GetComponentsInChildren<ParticleSystem>())
     {
         particleSystems.Add(system); //components in root will be swept up in this
      }
}

void Update()
{
    foreach(ParticleSystem system in particleSystems)
    {
         if(system!=null && system.IsAlive()) return;
     }
     Destroy(gameObject);
}

Privacy & Terms