Search code examples
c#unity-game-engineparticle-system

OnParticleTrigger(): How to get the collider a particle entered?


I am trying to extinguish a fire in Unity3d. I have 2 particle systems: fire and water. Since 2 particle systems can't collide, i added a box collider to the base of the fire (where isTrigger is checked). I use OnParticleTrigger() to damage the health of the fire. But now I want to have multiple fires so I need to know which fire/box collider a particle entered. I know you can't get the collider like OnTriggerEnter(), but is there a way to work around it?

I tried OnParticleCollision(), but the water particles bounce of the box collider (this is not the visual effect I want).


Solution

  • Each trigger event I get all the particles that entered a collider. Then, for each of those particles, I check which box collider they entered with collider.bounds.Contains() and damage the fire the box collider belongs to. I don't know if this is the best way to do it (probably not), but it works for now.

    private void OnParticleTrigger()  
        {
    
            //Get all particles that entered a box collider
            List<ParticleSystem.Particle> enteredParticles = new List<ParticleSystem.Particle>();
            int enterCount = waterPS.GetTriggerParticles(ParticleSystemTriggerEventType.Enter, enteredParticles);
    
            //Get all fires
            GameObject[] fires = GameObject.FindGameObjectsWithTag("Fire");
    
            foreach (ParticleSystem.Particle particle in enteredParticles)
            {
                for (int i = 0; i < fires.Length; i++)
                {
                    Collider collider = fires[i].GetComponent<Collider>();
                    if (collider.bounds.Contains(particle.position))
                    {
                        fires[i].GetComponent<Fire>().Damage();
                    }
                }
            }
        }