- Unity 2018 Cookbook(Third Edition)
- Matt Smith
- 263字
- 2025-02-23 18:56:39
How it works...
The key feature of this recipe is the new CreateAudioSource(...) method. This method takes input as a reference to a sound clip file and a Boolean true/false value as to whether the sound should start playing immediately. The method does the following:
- Creates a new GameObject (with the same parent, and at the same location as the GameObject doing the creating)
- Adds a new AudioSource component to the new GameObject
- Sets the audio clip of the new AudioSource component to the provided AudioClip parameter
- If the Boolean parameter was true, the AudioSource component is immediately sent a Play() message to start it playing the sound clip
- A reference to the AudioSource component is returned
The rest of the MusicManager script class is very similar to that in the previous recipe. There are two public AudioClip variables, clipMedieval and clipArcade, which are set through drag-and-drop at Design-Time to link to the sound clip files in Sounds Project folder.
The audioSourceMedieval and audioSourceArcade AudioSource variables are now private. These values are set up in the Awake() method, by calling and storing values returned by the CreateAudioSource(...) method with the clipMedieval and clipArcade AudioClip variables.
To illustrate how the Boolean parameter works, the medieval music AudioSource is created to play immediately, while the arcade music won't start playing until the UP arrow key is pressed. Playing/Resuming/Pausing the two audio clips is just the same as in the previous recipe – via the arrow-key detection logic in the (unchanged) Update() method.