/// <summary> /// The <c>Play</c> method plays a sound based on the <paramref name="clipName" />. /// </summary> /// <param name="clipName">Name of the <see cref="SoundClip" /> that should be played.</param> /// <returns>Returns a <see cref="AudioSource" /> created based on the settings defined in the <see cref="SoundClip" />.</returns> /// <exception cref="NullReferenceException"> /// Thrown when there is no <see cref="SoundClip" /> in the soundClips array named /// <paramref name="clipName" />. /// </exception> public AudioSource Play(string clipName) { // Get sound clip from array. SoundClip soundClip = Array.Find(soundClips, clip => clip.Name == clipName); if (soundClip == null) { throw new NullReferenceException($"There is no clip named {clipName.Bold()} found in the soundClips array."); } // Throw an ArgumentException when the sound clip is not a SFX and there is already an child object with the same name. if (!soundClip.IsSFX) { if (CachedTransform.Cast <Transform>().Any(child => child.name == clipName)) { throw new ArgumentException( $"There can only be one instance of the soundClip named {clipName.Bold()}. When I should have more instances it should be an SFX"); } } // Make a new game object named 'clipName', and set it as a child of this object. var clipGameObject = new GameObject(clipName); clipGameObject.transform.SetParent(CachedTransform); // Adding and setting up a audio source component. var audioSource = clipGameObject.AddComponent <AudioSource>(); audioSource.clip = soundClip.AudioClip; audioSource.volume = soundClip.Volume; audioSource.loop = !soundClip.IsSFX; audioSource.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Master")[0]; // Play the audio audioSource.Play(); // If the sound clip is a SFX destroy the game object when it is done playing. if (soundClip.IsSFX) { Destroy(clipGameObject, audioSource.clip.length + 0.1f); } // Return audio source. return(audioSource); }