Unity 3D: Play An Audio Source Directly In the Editor

11/17/2021 7:55:50 PM

Audio Sources make it very easy to play Audio Clips in Unity. They include a variety of options to tweak the sound. To play the sound however, you must make Editor changes and then go into Play mode. This wastes tons of time. The following is a super simple Component and Custom Editor to allow you to play the Audio Source, and all of its tweaks, directly in the Editor.

File 1: Component: AudioSourcePlayer.cs

This is a standard Unity Component that you will attach to the transform with the Audio Clip (I place it above the Audio Clip in the Inspector window).


using UnityEngine;

public class AudioSourcePlayer : MonoBehaviour
{
	internal void Play_Audio_Source()
	{
		//Debug.Log("AudioSourcePlayer: Play_Audio_Source");

		//get the audio source part of this transform and play it
		//this assumes there is only one audio source attached to this transform
		var audio_source = this.transform.GetComponent<AudioSource>();
		if (audio_source)
		{
			audio_source.Play();
		}
	}


	internal void Stop_Audio_Source()
	{
		var audio_source = this.transform.GetComponent<AudioSource>();
		if (audio_source)
		{
			audio_source.Stop();
		}
	}
}

File 2: Editor: AudioSourcePlayerEditor.cs

This holds the simple UI logic that will add the Button to the Inspector window and allow you to trigger the Audio Source.


#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(AudioSourcePlayer))]
public class AudioSourcePlayerEditor : Editor
{        
	private void OnEnable()
	{
		//Debug.Log("AudioSourcePlayerEditor: OnEnable");
		//Debug.Log(target);
		//Debug.Log(target.name);            
	}


	public override void OnInspectorGUI()
	{
		//Debug.Log("AudioSourcePlayerEditor: OnInspectorGUI");

		//this will draw the default inspector for the component you are inspecting
		//instead of using a new custom object, you could add editor options to AudioSource
		//DrawDefaultInspector would add the default inspection controls with our custom button at the bottom
		//I find it easier to use the custom component, add it above the AudiSource in the editor
		//that makes the play button easier to spot and click            
		DrawDefaultInspector();

		
		if (GUILayout.Button("Play Audio Source"))
		{
			//button logic
			//Debug.Log("AudioSourcePlayerEditor: OnInspectorGUI: Play Audio Source");

			var player = (AudioSourcePlayer)target;
			player.Play_Audio_Source();
		}
		

		if (GUILayout.Button("Stop Audio Source"))
		{			
			var player = (AudioSourcePlayer)target;
			player.Stop_Audio_Source();
		}
	}
}
#endif