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. Dismiss Notice

Question Random Zombie sounds

Discussion in 'Audio & Video' started by Toxitalk, Aug 1, 2022.

  1. Toxitalk

    Toxitalk

    Joined:
    Jul 13, 2022
    Posts:
    9
    I have a Zombie GameObject (character) and have attached an Audio Source to the inspector and its working fine.

    In my Zombie Audio Script Im using a CoRoutine to randomly play the sound (all good so far).

    What Im stuck on is that I would like the zombie to play one of a number of sounds.

    I am currently using the below to play the sound

    this.GetComponent<AudioSource>().Play();

    Am I able to add a second Audio Source component and switch between the two?

    Im only just started with Unity so please go gentle.

    Thanks.
     
  2. JLF

    JLF

    Joined:
    Feb 25, 2013
    Posts:
    137
    Hi!

    You can add multiple audio sources but, if your sounds are one-shot sounds, you'll probably be better off keeping one audio source and holding an array of random clips instead.

    Then when you want to play a random sound, use Play One Shot and pass in a new clip instead.

    Like this:

    Code (CSharp):
    1. public class PlayAudio : MonoBehaviour
    2. {
    3.   AudioSource audioSource;
    4.   public AudioClip[] audioClipArray;
    5.  
    6.   void Awake()
    7.   {
    8.     audioSource = GetComponent<AudioSource>();
    9.   }
    10.  
    11.   void PlayRandomClip()
    12.   {
    13.  
    14.     AudioClip nextClip = audioClipArray[Random.Range(0, audioClipArray.Length)];
    15.     audioSource.PlayOneShot(nextClip);
    16.   }
    17. }
    For more on this, such as how to play a random clip with no repeats, I wrote an article about the basics of playing audio in Unity here: https://gamedevbeginner.com/how-to-play-audio-in-unity-with-examples

    Hope that helps!