- Home /
Retaining Reference to Singleton GameObject
I'm pretty new to Unity, so bear with me.
As part of the game I'm making, I created a GameObject called "Music", and attached an AudioSource to and made it into a Singleton with code I found from a tutorial
void Awake()
{
if (instance != null && instance != this)
{
Destroy(this.gameObject);
return;
}
else
{
instance = this;
}
DontDestroyOnLoad(this.gameObject);
}
I also created another script for handling of pausing which should allow the user to turn the music off and also to restart the level. Since I found issues with traversing the hierarchy to get to this object, I instead pass the object as a parameter (dragging and dropping).
The issue is that when I restart the level (by reloading the Scene) - the Destroy code occurs, and I get this error message:
The object of type 'GameObject' has been destroyed but you are still trying to access it
How can I ensure that I retain the reference?
The code I'm using is here
// Class Object
public GameObject MusicHandler;
// -- SNIP -- within OnGUI function
var music = MusicHandler.GetComponent<AudioSource>(); //crash happens
Answer by fafase · May 04, 2014 at 12:17 PM
Here is how I keep my sound object at all time:
public class Sound: MonoBehaviour {
public GameObject audioPrefab;
private GameObject audioObject = null;
protected virtual void Awake ()
{
string str = "AudioObject";
GameObject o = GameObject.Find (str);
if(o == null)
{
o = (GameObject)Instantiate(audioPrefab, Vector3.zero, Quaternion.identity);
o.name = str;
DontDestroyOnLoad(o);
audioObject = o;
}
else
{
audioObject = o;
}
}
}
You create an audio object prefab, and you drag it into the audioPrefab slot.
You can attach this script to a game manager that is over all scenes where you want that music to continue.
Then that allows to restart the scene, get to the next scene without losing your object and music won't stop when changing scene.
If you would get to a scene where the music is different, either you change the audio clip or you destroy that object. When you get back to that scene where you need that audio object, it is created again.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
using non static variable in static function 1 Answer
Animation Problems 1 Answer
Error in a really short script 2 Answers