Passing Score from Game Scene to Game Over Scene usiing dontDestroyOnLoad C#
Hi guys please help, trying to save the score from game scene to gameover scene,
have this so far but doesn't work
This one below is from the game scene. I created an empty gameobject which obtains the score from the scoreboard which i didn't want to carry on to the next scene because it had to many other methods.
public class CurrentScoreTracker : MonoBehaviour {
public ScoreControl Score;
public int score;
// Use this for initialization
void Awake () {
Score.currentScore = score;
DontDestroyOnLoad (transform.gameObject);
}
}
This one is the Scoreboard for the GameOver Scene
public class GameOverScore : MonoBehaviour {
public CurrentScoreTracker trackedScore;
public int currentScore;
public Text ScoreBoard;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
currentScore += trackedScore;
ScoreBoard.text = "SCORE : "+currentScore.ToString ();
}
}
If this is not a good way to track score from one scene to another, please recommended me a better way.
Thanks in advance.
Answer by Ali-hatem · Feb 27, 2016 at 12:06 PM
you have to carry the gameobject to the next scene if it have to many methods make another gameobject and attach a script with only dontdestroyonload method and score variable by the way you should add the gameobject to the next scene by drag and drop as a brefap .
public class CurrentScoreTracker : MonoBehaviour {
public static CurrentScoreTracker CST; //this line will give you access to this script without the ned of getcomponent.
public int score;
void Awake () {
if (CST== null)
{
DontDestroyOnLoad(gameObject);
CST= this;
}
else if (CST!= this)
{
Destroy(gameObject);
}
}
//now increase the score from the GameOverScore script :
public class GameOverScore : MonoBehaviour {
public int currentScore;
public Text ScoreBoard;
void Update () {
currentScore +=1;
CurrentScoreTracker.CST.score = currentScore;
ScoreBoard.text = "SCORE : "+currentScore.ToString ();
}
}
That is what I did. I made another object obtaining the score from the script which has a lot of other methods. Right now I'm not sure on what to do because there is no object to drag into the inspector while in scene mode. The object only exist when it is in game view because of the dontdestroyonload method.
So the solution you are suggesting is to make a prefab and drag the prefab in the last scene and then drag it into the inspector?
So to confirm, which object am I making a prefab for. Is it the first game object from the game scene?
yes the first game object from the game scene so make it a brefab and in any scene drag it back to the hierarchy but you should have another script in the game over scene to access the CurrentScorerTracker script to obtain the score value.