Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Help Wanted Two sounds does not work ?

Discussion in 'Scripting' started by Quast, Jun 12, 2020.

  1. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    521
    I'm using unity 19.3.13f1 version. In my script there are two sounds (emptyObject with audioSource attached) play when get near J object. But it does not work !! Like a bug maybe. Here is my script
    Code (CSharp):
    1.  
    2.     public AudioSource a, b;
    3.     public GameObject j;
    4.     public float distance;
    5.  
    6.     // Update is called once per frame
    7.     void Update()
    8.     {
    9.         distance = Vector3.Distance(gameObject.transform.position, j.transform.position);
    10.         if (distance <= 5)
    11.         {
    12.             a.GetComponent<AudioSource>().Play();
    13.             b.GetComponent<AudioSource>().Play();
    14.  
    15.         }
    16.         else
    17.         {
    18.             a.GetComponent<AudioSource>().Stop();
    19.             b.GetComponent<AudioSource>().Stop();
    20.         }
    21.     }
    Did anyone notes it ?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    3,767
    Since this is in Update(), you're restarting the audio clip every frame by calling Play() every frame.
     
    Quast and Joe-Censored like this.
  3. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    521
    Ok. what to do when "A" sound is play once, and "B" sound is a loop. How to solve this ?
     
unityunity