Search Unity

Question Kill specific particle through script

Discussion in 'Editor & General Support' started by Crawdad, Mar 4, 2023.

  1. Crawdad

    Crawdad

    Joined:
    Nov 23, 2016
    Posts:
    174
    I've been trying like hell to figure out how to do this and have come up short. How do you kill a specific particle through script? Setting ParticleSystem.Particle.remainingLifetime = 0 doesn't seem to do anything. Would love any ideas on how to accomplish this. Sample script I'm working with below. Using Unity 2021. Thanks in advance.
    Code (CSharp):
    1.      
    2.     ParticleSystem ps;
    3.     ParticleSystem.Particle[] particles;
    4.  
    5.         // get the alive particle count and assign particles to particles
    6.         int numParticlesAlive = ps.GetParticles(particles);
    7.  
    8.         // iterate through the alive particles
    9.         for (int i = 0; i < numParticlesAlive; i++)
    10.         {
    11.             var position = particles[i].position;
    12.             Collider[] hitColliders = Physics.OverlapSphere(position, collisionRad, colliderMask);
    13.             if (hitColliders.Length > 0)
    14.             {
    15.                 hitColliders = Physics.OverlapSphere(position, damageRad, damageMask);
    16.                 foreach (Collider enemy in hitColliders)
    17.                 {
    18.                     //Deal damage
    19.                 }
    20.                 particles[i].remainingLifetime = 0; //This doesn't work
    21.             }
    22.         }
    23.  
     
    Last edited: Mar 4, 2023
  2. Crawdad

    Crawdad

    Joined:
    Nov 23, 2016
    Posts:
    174
    Got it figured out. Replaced line 20 with the following.

    Code (CSharp):
    1.                
    2. particles[i].remainingLifetime = 0.05f; //Must be above 0 to work properly
    3. ps.SetParticles(particles, numParticlesAlive);  //This must be included to apply changes to particles
    4.  
     
  3. richardkettlewell

    richardkettlewell

    Unity Technologies

    Joined:
    Sep 9, 2015
    Posts:
    2,285
    You got it. You can restrict the SetParticles call to update just that one particle too, to make it a bit more efficient.
     
    Crawdad likes this.
  4. Crawdad

    Crawdad

    Joined:
    Nov 23, 2016
    Posts:
    174
    Appreciate the feedback. Would be interested in knowing how to restrict it to just the one particle, if you don't mind dumbing it down for me.

    Also, are you aware of a good way to get the index of the individual particles? I'm having a heck of a time figuring out a good way to keep track particles as they are enabled and disabled. For example, the array "particles" generated in line 6 seems to shift the index of particles as they are enabled/disabled. Would love to see an explanation of how the particle system orders the particles in the array. Thanks in advance.
     
    Last edited: Mar 9, 2023