Search Unity

How can I play audio Randomly ?

Discussion in 'Getting Started' started by Lupinder, Jun 24, 2020.

  1. Lupinder

    Lupinder

    Joined:
    Oct 6, 2018
    Posts:
    85
    I have two audio files but ı dont how can ı play them randomly. I want to add audio files by script and ı want to play them randomly. Thanks for help.

    Code (CSharp):
    1. public class GrapplingHook : MonoBehaviour {
    2.         public AudioClip _soundd;    // this lets you drag in an audio file in the inspector
    3.         public AudioSource audioo;
    4.         public GameObject otherObject;
    5.         Animator otherAnimator;
    6.         void Start()
    7.         {
    8.             otherAnimator = otherObject.GetComponent<Animator>();
    9.             audioo = audioo; //oadds an AudioSource to the game object this script is attached to
    10.             audioo.playOnAwake = false;
    11.             audioo.clip = _soundd;
    12.             audioo.Stop();
    13.         }
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Please don't post duplicate threads. If you find your question gets no responses, try posting a followup (in the same thread) with more detail. Usually questions go unanswered because they were too vague or unclear to have an answer.

    To your (really quite vague) question, you would simply have two AudioClip (or two AudioSource) references in your script, and use Random.value with an if statement to play one or the other.
     
  3. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    JoeStrout likes this.