- Home /
Keeping a score from one scene to another?
My game is keeping track of a high score. I want this score to display when the scene changes to the win Screen. I'm a bit confused as to how to go about doing this. I have the DontDestroyOnLoad line in my script, but how would I go about actually calling the variable into my new scene? Since it's a new scene, the script doesn't actually exist in that scene yet. Would I have to copy and paste the script into the assets folder in the new scene or would I have to call if through code, and if so, how?
Thanks for the help.
Hi BCouto, correct me if I'm wrong, where and how did you call DontDestroyOnLoad? I'm assu$$anonymous$$g you attached it to a gameobject that 'keeps track' of the score. If the method call was successful, you should be able to reference that script attached to the gameObject from any script existing in the new scene.
Also, you may want to check out this similar question that was answered some months back. $$anonymous$$ay give you another option for setting level stats throughout your game.
Sorry, forgot to add the link: http://answers.unity3d.com/questions/9996/singleton-score-keeping-and-ongui-updates
Answer by Lab013 · Mar 18, 2011 at 06:36 AM
Just to make sure you're doing this:
function Start() {
DontDestroyOnLoad(gameObject);
}
What that does, is whenever you load a new level, the object (and its scripts) won't be destroyed.
There are other ways to do this though. You could have a script like this:
// I'm going to pretend this scripts name is MyScript static var score : int = 100;
function OnGUI() { GUILayout.Label("Your Score: " + score);
}
Then in another script you could do something like this
function KillEnemy() {
++MyScript.score;
} // Award the player 10 points
Because score is a static variable, there is only one instance of that particular variable. You don't need a class instance to access that variable, it can be accessed from anywhere just by using the ClassName.variable syntax.
Thanks Lab013, just the answer I needed! (I don't seem to be able to upvote your response?)
B
Is it fine if I save that another script from other scene?
here is my problem " DontDestroyOnLoad(gameObject); " is working fine...but i set my game that my player only have 1 live and return to 1st scene when he die...whenever this happen...my score didn't reset itself back to 0...it only gains more and more points...how do i reset this when my player die and still keep the high score? do i need to do this in different script? score script and high score script? well that's a thought...hmmm...but not entirely sure...
Answer by Atnas1010 · Oct 29, 2010 at 05:12 AM
You could do something like this:
public var score : float;
function OnGUI() { if (Application.loadedLevelName == "WinScene") GUILayout.Label(score.ToString()); }