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!

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;
}

Hi somehow it still gives me a NullReference Exception :frowning: