- Home /
Making a reference to a script that DontDestroyOnLoad
Hello,
I am trying to make a script called "AudioFactory" that handles all audio related operations for my game (music & SFX). To ensure that it exists throughout the game, I placed the script in an empty game object called "_persistents," and called DontDestroyOnLoad(gameObject) in its start method. The problem I am now having is making a reference to it so that scene specific scripts can call its methods, because _persistent is instantiated in the MainMenuScene.
I have also tried making the methods static, but this requires (I think) that all variables are static, which is not what I want.
Is there a way to make a reference to a script that DontDestroyOnLoad? And also, am I approaching audio handling correctly, or is there a better way to approach it?
Thanks!
Answer by supernat · May 30, 2014 at 04:34 PM
I was going to suggest making it mostly static, but you already thought of that. So I'll just suggest making the instance static (make it a singleton). Something like this:
private static AudioFactory _instance;
void Awake() {
_instance = this;
}
public static AudioFactory GetInstance() { return _instance; }
Now you can access the script that is attached to a single game object by calling AudioFactory.GetInstance(). Just make sure you don't attach it more than once. In fact you can add this to help with that:
void Awake() {
if (_instance != null) {
Debug.Log("Dummy, you attached me twice!"); // Sorry that's how I talk to myself through code!
return;
}
_instance = this;
}
Works like a charm. I remember you helping me back when I was having difficulty setting up my android device - thanks again!
No problem, glad to help. If you have some spare change, you might also check out the Asset Store. There are quite a few good audio plugins on there, some that will randomly choose music/sound effects, handle object pooling, etc.
thanks man! you saved my day(night) i was about to give up
Answer by SkillcraftHD · Dec 30, 2020 at 10:24 PM
Hi somehow it still gives me a NullReference Exception :(
Your answer

Follow this Question
Related Questions
Menu music stops playing after returning from game level 0 Answers
How to STOP music when loading a SPECIFIC SCENE? 3 Answers
Don't destroy a variable when changing scene 2 Answers
How to stop audio in a scene when DontDestroyOnLoad was already called? 1 Answer
MissingReferenceException in AudioSource on DontDestroyOnLoad GameObject 0 Answers