- Unity 2018 Cookbook(Third Edition)
- Matt Smith
- 257字
- 2025-02-23 18:56:39
Adding the CreateAudioSource(...) method as an extension to the MonoBehavior class
Since the CreateAudioSource(...) method is a general-purpose method that could be used by many different game script classes, it doesn't naturally sit within the MusicManager class. The best place for general-purpose generative methods such as this is to add them as static (class) methods to the component class they work with – in this case it would be great if we could add this method to MonoBehavior class itself – so any scripted component could create AudioSource GameObjects on the fly.
All we have to do is create a class (usually named ExtensionMethods) with a static method, as follows:
using UnityEngine; public static class ExtensionMethods { public static AudioSource CreateAudioSource(this MonoBehaviour parent, AudioClip audioClip, bool startPlayingImmediately) { GameObject audioSourceGO = new GameObject("music-player"); audioSourceGO.transform.parent = parent.transform; audioSourceGO.transform.position = parent.transform.position; AudioSource newAudioSource = audioSourceGO.AddComponent<AudioSource>() as AudioSource; newAudioSource.clip = audioClip; if (startPlayingImmediately) newAudioSource.Play(); return newAudioSource; } }
As we can see, we add an extra first parameter to the extension method, stating which class we are adding this method to. Since we have added this to the MonoBehavior class, we can now use this method in our scripted classes as if it were built-in. So our Awake() method in our MusicManager class looks as follows:
void Awake() { audioSourceMedieval = this.CreateAudioSource(clipMedieval, true); audioSourceArcade = this.CreateAudioSource(clipArcade, false); }
That's it – we can now remove the method from our MusicManager class and use this method in any of our MonoBehavior scripted classes.