- Home /
Don't Destroy on Load not working for me
Unless another part of the code or setup is wrong. But as you see in the images below, I have a game set up screen, and you select a difficulty option by clicking (check marking) a small box there, then after you select one, hitting "Start Game" is supposed show the option you chose in the next scene (the image with the isometric view, its supposed to replace that text object, but I guess it just gets destroyed.), but it doesn't.
Ignore the "submit" button lol.
It's like no matter where I put "dont destroy on load" it just doesnt work.
public Toggle isEasy;
public Toggle isNormal;
public Toggle isHard;
public Toggle isCrazy;
public Text textObject;
private void Awake()
{
DontDestroyOnLoad(textObject);
}
public void Start()
{
textObject.enabled = false;
}
//check active toggle
public void ActiveToggle()
{
if (isEasy.isOn)
{
Debug.Log("Player selected easy");
}
else if (isNormal.isOn)
{
Debug.Log("Player selected normal");
}
else if (isHard.isOn)
{
Debug.Log("Player selected hard");
}
else if (isCrazy.isOn)
{
Debug.Log("Player seleced crazy");
}
}
public void OnStart() //our button
{
//submitting difficulty selection
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
Debug.Log("Difficulty selected");
textObject.enabled = true;
//check active toggle through function
ActiveToggle();
}
}
Answer by AaronBacon · Nov 26, 2020 at 03:39 AM
I believe your problem may be that you're calling DontDestroyOnLoad on the Text Component of the Game Object, not the game object itself, try changing DontDestroyOnLoad(textObject);
to DontDestroyOnLoad(textObject.gameObject);
does it matter where its located in the code and is private void Awake() the correct function for it?
Also, I think a problem is its not reading my toggle system. I tested it by changing whats in the Void Start () to true and it just came up as New Text on the next scene.
But it does say "difficulty selected" after hitting start game. So for whatever reason, the text on the next scene is not changing to the difficulty that was selected its staying as "New Text". It also said "player selected easy" its just that text on the next scene doesn't wanna change to it. I get this error in the Awake function: "Object reference not set to an instance of an object "
As I said, I believe the object isn't being preserved through scenes because you're targeting the component on the gameObject, which will still be destroyed when the gameObject itself is unloaded, hence the error you're getting that it can't find the object you're trying to activate upon going to the next scene. Awake acts similar to start, but before it, so its a good place to use DontDestroyOnLoad