Hi I managed to implement random sounds in my game by having a snoop around in the Keyboard.cs script from the Terminal Hacker game, which had a random sound from a set of 4 different sounds each time the player pressed a key on the keyboard. Using that as a basis I came up with this
void Start () { rigidBody = GetComponent<Rigidbody>(); audioSource = GetComponent<AudioSource>(); // links audioSource variable to gameObject } private void PlayRandomSound() { int randomIndex = UnityEngine.Random.Range(0, fartThrusters.Length); audioSource.clip = fartThrusters[randomIndex]; audioSource.Play(); } // Update is called once per frame void Update() { ProcessInput(); } private void ProcessInput() { if (Input.GetKey(KeyCode.Space)) //can thrust while rotating { rigidBody.AddRelativeForce(Vector3.up); if (audioSource.isPlaying == false) { PlayRandomSound(); } } if (Input.GetKey(KeyCode.A)) { transform.Rotate(Vector3.forward * Time.deltaTime *10); //corisponds to left } else if (Input.GetKey(KeyCode.D)) { transform.Rotate(-Vector3.forward * Time.deltaTime *10); //opposite to left } } }
When I did this, a field appeared in the Inspector under my rocket script called Fart Thrusters which allowed me to specify the āsizeā of the field and enter multiple different sounds from my assets like this.
So now when i press or hold the space-bar it will play 1 of these 5 different random sounds. Hopefully someone else may find this useful.
Regards.
PS if an admin is able to spot anything unnecessary in the above code please let me know so I can refine it. Many thanks.