I have 23 different GUI Buttons that each need to play their respective Audio Clip, each labeled as Track1, Track2, etc. The audio tracks are all Audio Sources in the Game Object, but I’m confused as to how to make the individual buttons play the respective tracks. Would I need to make a var audio: AudioSource for every audio track I have and label them individually? Also, the Debug.Log is a placeholder until I can figure out what to do there. Sorry if I’m missing something very basic. Here is an example of my code:
using UnityEngine;
using System.Collections;
public class Buttons : MonoBehaviour {
void OnGUI() {
if (GUI.Button(new Rect(430,50,80,30), "Track 1"))
Debug.Log ("Clicked Button");
if (GUI.Button(new Rect(530,50,80,30), "Track 2"))
Debug.Log("Clicked Button");
I would store the audio clips in an array. That way you can iterate over them using a for loop and generate your buttons on the fly with a minimum of code
using UnityEngine;
using System.Collections;
public class Buttons : MonoBehaviour {
// Your 23 sounds are assigned to that array in the inspector.
// The code also allows for any other number of sounds
public AudioClip[] sounds;
public float leftmostButton = 430f;
public float delta = 100f;
void OnGUI() {
for (int i = 0; i < sounds.Length; ++i){
if (GUI.Button(new Rect(leftmostButton + delta * i, 50, 80, 30), "Track " + i)){
audio.PlayOneShot(sounds*);*
You can make that by put a Audio Source in a gameobject and when the gui is pressed you can specify the track by audio.clip and then play the song by audio.Play.