To play multiple sounds using the same AudioSource component, perform the following steps:
- Create a new Unity 2D project and import the sound clip files.
- Create a C# script class, called PlaySounds, in a new folder, _Scripts, that contains the following code. Additionally, add an instance as a scripted component to the Main Camera:
using UnityEngine; [RequireComponent(typeof(AudioSource))] public class PlaySounds : MonoBehaviour { public AudioClip clipEatCherry; public AudioClip clipExtraLife; private AudioSource audioSource; void Awake() { audioSource = GetComponent<AudioSource>(); } void Update() { if (Input.GetKey(KeyCode.UpArrow)) audioSource.PlayOneShot(clipEatCherry); if (Input.GetKey(KeyCode.DownArrow)) audioSource.PlayOneShot(clipExtraLife); } }
- Ensure that the MainCamera GameObject is selected in the Hierarchy panel. Then, in the Inspector panel...