Implemented Random Sounds

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.
fartthrusters

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.

1 Like

ā€œfartsā€ are fine, other forms of profanity are removed as we do have a younger audience as well on the forum/in the community. Thanks for asking though :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms