Tuesday, April 26, 2016

Creating a MusicController Module in Unity 3D C#

In Unity3D or any game engine you sometimes need music to play across multiple scenes. To accomplish this in Unity3D you need to create a MusicController GameObject that doesn't destroy on load. Below I do this with a Singleton Class that retains from scene to scene! Game.music is a static boolean field that tells rest of the system that music is enabled. On this controller I have an array of AudioClip[]. which I can have songs in ogg or mp3 format.




using UnityEngine;
using System.Collections;
using System;
using System.IO;
using Prime31;

public class MusicController : MonoBehaviour {

#region Music
public static MusicController Instance { get; private set; }
public AudioClip[] Tracks;
int currentTrack=0;
public void Awake() {
if (!Game.music) {
Instance = null;
Destroy(gameObject);
return;
}
if (Instance!=null) {
Destroy(gameObject);
GetComponent<AudioSource>().Stop();
}
if (Instance==null) {
Instance = this;
DontDestroyOnLoad(this.gameObject);
}
}
public string trackName() {
string x = "";
if (GetComponent<AudioSource>().clip!=null)
x = GetComponent<AudioSource>().clip.name;
return x;
}

public void playRandomTrack(bool t) {

GetComponent<AudioSource>().Stop();
GetComponent<AudioSource>().enabled = true;
int x = UnityEngine.Random.Range(0,Tracks.Length);
GetComponent<AudioSource>().clip = Tracks[x];
GetComponent<AudioSource>().Play();
currentTrack = x;
if (GUI.Instance!=null)
GUI.Instance.ShowTextToast("Track: " + trackName(),5f);
}


public void playRandomTrack() {

playRandomTrack(true);
}

public void Start() {

if (Game.music) {
Instance = null;
playRandomTrack();
Awake();
return;
}
}

public void Update() {

if (!Game.music) {
Instance = null;
Destroy(gameObject);
return;
}

if (!GetComponent<AudioSource>().isPlaying && GetComponent<AudioSource>().clip!=null)

playRandomTrack();
if (Game.gameOver) {
GetComponent<AudioSource>().volume = 0.75f;
} else if (Game.shouldBegin)  {
GetComponent<AudioSource>().volume = 0.25f;
} else GetComponent<AudioSource>().volume = 0.75f;
}
#endregion

}

No comments:

Post a Comment

Generating "Always On Top" NSWindow in macOS across all detected displays

Also: Using UIKit & Cocoa Frameworks using Objective-C In m acOS or OS X , written in either Objective-C or Swift  Langues, you m...