- Home /
Reference to script in callback goes missing when scene reloads
TL;DR I have a GameManager Object with an AudioManager script. The object is set to not be destroyed on reload. Though a reference to it goes missing from a menu when the main menu scene reloads.
This may be a misunderstanding on my part of how DontDestroyOnLoad(gameObject); works, but i have a settings menu with a button that controls the music playing in the background.
After one round of game play (gameplay being in another scene) and returning to the main menu scene, the object holding the audiomanager script that is supposed to be referenced in the music toggle button is missing.
But, I have that gameobject set to not be destroyed on load. What could the issue be? Or what is my misunderstanding here?
Edit: I realized i was basically making my own OnClick event, so i tried just adding one for the ToggleMusic function and the same result occurs, the GameManager object itself becomes missing. I tried turning the GameManager into a prefab but nothing changed. So the bug persists.
FIXED: TL;DR: make the callback object a prefab. $$anonymous$$ake sure you are referencing the correct thing to avoid null reference exceptions.
So here's what i did. I found others saying that turning the gamemanager object into a prefab and then dragging the prefab (not from the scene hierarchy) into the callback would work. However i kept getting null reference exceptions whenever i tried to Play or Stop sounds from the audiomanager script on the gamemanager prefab. (Game$$anonymous$$anager prefab contains Audio$$anonymous$$anger script, which is a singleton)
public class Audio$$anonymous$$anager : $$anonymous$$onoBehaviour
{
public Sound[] sounds;
public static Audio$$anonymous$$anager instance;
// Start is called before the first frame update
void Awake()
{
if(instance == null) {
instance = this;
}
else {
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
foreach(Sound s in sounds) {
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
}
Problem has to do with how i was referencing the list of sounds that is on the Audio$$anonymous$$anager. I was previously using the line:
Sound s = Array.Find(sounds, sound => sound.name == name);
But i changed it to:
Sound s = Array.Find(Audio$$anonymous$$anager.instance.sounds, sound => sound.name == name);
I think because i was using the prefab and not the Game$$anonymous$$anager instance (even though it is made from the prefab) it wasn't finding the sounds array that i had on the prefab script so it needed to reference the instance on the gameobject made from the prefab. Im not even sure if thats it but i know that the issue is fixed!