How can i make my particle system emit a sound everytime it enters the collider?

hello, i am new to Unity and i was trying to get my particles to emit a sound everytime they hit the collider with this script, but it just plays it one time and that’s it, i can’t even manage to put a delay on it.
help please?

public class TriggerScript : MonoBehaviour
{
    ParticleSystem ps;
    List<ParticleSystem.Particle> enter = new List<ParticleSystem.Particle>();
    public AudioClip sound;
    void OnEnable()
    {
        ps = GetComponent<ParticleSystem>();
        AudioSource audio = GetComponent<AudioSource>();
        void OnParticleTrigger()
        {
            {
                int numEnter = ps.GetTriggerParticles(ParticleSystemTriggerEventType.Enter, enter);
                for (int i = 0; i < numEnter; i++)
                {
                    ParticleSystem.Particle p = enter;
                    audio.PlayOneShot(sound);
                }
            }
        }
    }
}

I don’t even know what is going on there with the OnParticleTrigger function inside of an OnEnable function. Are you sure it even compiles? Either way, I don’t think you want it that way, and I doubt it would work.

Have you tried starting with the example in the docs and incrementally changing it to suit your needs?

i’ve started from this
https://docs.unity3d.com/Manual/PartSysTriggersModule.html

Notably, that example does NOT have a nested function the way you do.

See the way OnParticleTrigger is “inside” the body of OnEnable?

That means it does not exist as far as the class is concerned. It is a local function.

Look at the code again in the example you linked. Note those functions are NOT contained within each other.

1 Like