- Unity 2018 Cookbook(Third Edition)
- Matt Smith
- 281字
- 2025-02-23 18:56:39
How to do it...
To play different sounds each with their own AudioSouce component, do the following:
- Create a new Unity 2D project and import the sound clip files.
- Create a GameObject in the scene containing an AudioSource component linked to the 186772__dafawe__medieval AudioClip. This can be done in a single step by dragging the music clip from the Project panel into either the Hierarchy or Scene panels. Rename this new GameObject to music1_medieval.
- Repeat the previous step to create another GameObject named music2_arcade, containing an AudioSource linked to 251461__joshuaempyre__arcade-music-loop.
- For both AudioSources created, uncheck the Play Awake property – so these sounds do not begin playing as soon as the scene is loaded.
- Create an empty GameObject named Manager.
- Create a C# script class, MusicManager, in a new folder, _Scripts, containing the following code, and add an instance as a scripted component to the Manager GameObject:
using UnityEngine; public class MusicManager : MonoBehaviour { public AudioSource audioSourceMedieval; public AudioSource audioSourceArcade; void Update() { if (Input.GetKey(KeyCode.RightArrow)){ if (audioSourceMedieval.time > 0) audioSourceMedieval.UnPause(); else audioSourceMedieval.Play(); } if (Input.GetKey(KeyCode.LeftArrow)) audioSourceMedieval.Pause(); if (Input.GetKey(KeyCode.UpArrow)){ if (audioSourceArcade.time > 0) audioSourceArcade.UnPause(); else audioSourceArcade.Play(); } if (Input.GetKey(KeyCode.DownArrow)) audioSourceArcade.Pause(); } }
- Ensure that the Manager GameObject is selected in the Hierarchy. In the Inspector panel, drag the music1_medieval GameObject from the Scene panel into the public Audio Source Medieval AudioSource variable in the MusicManager (Script) scripted component. Repeat this procedure, dragging GameObject music2_arcade into the public Audio Source Arcade variable.
- Run the scene, and press the UP and DOWN arrow keys to start/resume and pause the medieval sound clip. Press the RIGHT and LEFT arrow keys to start/resume and pause the arcade sound clip.