Search Unity

Stopping a sound clip from another script

Discussion in '2D' started by Feretro, May 24, 2018.

  1. Feretro

    Feretro

    Joined:
    Apr 18, 2017
    Posts:
    57
    Hello Everyone! Yes Of course I am a noob! ;-) I'd like to ask you a question. I am learning trying to follow Youtube's tutorials and ...

    I have got a Gameobject called (of course) "Player". This GameObject has two scripts attached let's call

    a.cs and
    b.cs.

    In the a.cs script I've got an AudioSource array

    Code (CSharp):
    1. public AudioSource[] suoni;
    so that I can call from this script something like

    Code (CSharp):
    1.  suoni[1].Pause();
    2.  suoni[0].Play();
    Now, in the b.cs script I've got some collider detection to ... "kill" my player. And well, if the player is dead ... he can't grumble anymore so I need to stop one of the sound clip of the first (a.cs) script.

    How can I call the function to stop sound clip in the first script from the second script?

    Thanks and sorry for wasting your time! :)
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Create a reference to your audio script in your second script, then reference the AudioSource array from that script.
    For example:

    Code (CSharp):
    1. public class B {
    2.  
    3.    //Drag script A here from the inspector.
    4.    public A audioScript;
    5.  
    6.    void OnCollisionEnter(Collision other) {
    7.       //When some collision happens and the player dies
    8.       audioScript.suoni[1].Pause();
    9.       audioScript.suoni[0].Play();
    10.    }
    11. }
    Alternatively, because both scripts are on the same object, you don't need to make a public reference to script A, and can instead use GetComponent to reference it in script B:
    Code (CSharp):
    1. public class B {
    2.  
    3.    private A audioScript;
    4.  
    5.    void Start() {
    6.       audioScript = GetComponent<A>();
    7.    }
    8.  
    9.    //The rest of the code
    10. }
    It doesn't really matter which way you do it.
     
    Last edited: May 24, 2018
  3. Feretro

    Feretro

    Joined:
    Apr 18, 2017
    Posts:
    57
    Thank you very much Cucci! It worked! :) I tried the second way ... But what do you mean by "Drag Script A here from the inspector" ? I never did that in a tutorial, yet. You literally mean pic the script from Unity Inspector (Non assets?), and drag into "Visual Studio" ?

    Yes, Yes, I must confess ... I am not just a noob. I am less than that!