Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

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

Discussion in 'Scripting' started by isabelva, Nov 18, 2019.

  1. isabelva

    isabelva

    Joined:
    Oct 14, 2019
    Posts:
    2
    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?

    Code (CSharp):
    1. public class TriggerScript : MonoBehaviour
    2. {
    3.     ParticleSystem ps;
    4.     List<ParticleSystem.Particle> enter = new List<ParticleSystem.Particle>();
    5.     public AudioClip sound;
    6.     void OnEnable()
    7.     {
    8.         ps = GetComponent<ParticleSystem>();
    9.         AudioSource audio = GetComponent<AudioSource>();
    10.         void OnParticleTrigger()
    11.         {
    12.             {
    13.                 int numEnter = ps.GetTriggerParticles(ParticleSystemTriggerEventType.Enter, enter);
    14.                 for (int i = 0; i < numEnter; i++)
    15.                 {
    16.                     ParticleSystem.Particle p = enter;
    17.                     audio.PlayOneShot(sound);
    18.                 }
    19.             }
    20.         }
    21.     }
    22. }
     
    Last edited: Nov 18, 2019
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    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?

    https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnParticleTrigger.html
     
  3. isabelva

    isabelva

    Joined:
    Oct 14, 2019
    Posts:
    2
    i've started from this
    https://docs.unity3d.com/Manual/PartSysTriggersModule.html
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    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.
     
    palex-nx likes this.