- Home /
DontDestroyOnLoad not working
I have a button in my game that allows the player to go back to the title screen mid-game. In order to save the score in such an occurrence, I put the score in the following class:
using UnityEngine;
using System.Collections;
public class Score : MonoBehaviour {
// This class contains the score and saving variables.
public int intScore;
public float decScore;
public bool keepScore; // This is to determine whether to keep or throw out the old score upon starting the game.
void Awake () {
DontDestroyOnLoad(this); // This makes sure the score stays as long as the app is open
if (FindObjectsOfType(GetType()).Length > 1)
{
Destroy(gameObject);
}
}
}
The intention is that a false value in keepScore indicates that the game is over and thus the score should not be kept, whereas a true value indicates that the game is in progress and thus the score should be kept. When the game ends, the value is set to false with a simple
score.keepScore = false;
(I am accessing it from another class) and when the game is in progress but the title screen is available to be selected the value is set to true with
score.keepScore = true;
However, when I go back to the title screen using the following code:
if (Input.touchCount == 1 && touched == false)
{
Application.LoadLevel("StartScreen");
}
and then return to the game, the value is always false, even if I had set it to true. What am I doing wrong?
Does this Score object already exist in the scene that you are loading? It could be re-initializing it somehow. Check the scene's object hierarchy when you load StartScreen. There could be a duplicate object.
Answer by MagicoCreator · Jan 27, 2014 at 08:33 PM
if you want it to exist you can consider using static variables instead of singleton mechanisms
even though if you plan to stick to the singleton version, i would recommend checking the what scripts can set it to false, or if your start funtion can write it.
another guess is that you're using DontDestroyOnLoad(this) which only protects the instance of the class but if the object which holds it is destroyed it might get desroyed along with it, try
DontDestroyOnLoad (transform.gameObject);
Thank you for pointing out the solution that was right under my nose!
Your answer
Follow this Question
Related Questions
Update() method is not called 0 Answers
DontDestroyOnLoad not working in Unity 4.3 1 Answer
is it OK to use DestroyImmediate in game? 4 Answers
Singleton DontDestroyOnLoad data persistance 0 Answers
DontDestroyOnLoad problem 1 Answer