- Home /
Save/Add score while different level load
I have the following script, for my score card. The issue, I'm facing is when the next level(scene) is loaded the score starts from 0. Please fix the code for me so that it save the score of current scene and add the next level score into it whenever next level is loaded! Note: I had used Do not destroy but it haven't worked for me! Script: var score = 0; var scoreText = "Score: 0"; var mySkin : GUISkin;
function OnTriggerEnter(other : Collider ) {
if (other.tag == "Pickup") { //Pickup is the tag for coin
Debug.Log("Other object is a coin");
score += 1; //Score integer
scoreText = "Score: " + score;
Debug.Log("Score is now " + score);
Destroy(other.gameObject);
}
}
function OnGUI () {
GUI.skin = mySkin;
GUI.Label (Rect (200, 10, 200, 400), scoreText.ToString());
}
Answer by clunk47 · Dec 17, 2012 at 02:25 AM
Make the score variable static.
EDIT: DoNotDestroyOnLoad not needed if using static. (Special thanks @fafase)
If I have to write a script for you it will be a a while because I'm working, but I will get to it later if you dont' figure it out.
Thanks for your kind response. I'll try again at my end and also please try to send my your script too when you get time! Thanks once again!
Thanks clunk it's working now for me after adding static. I had not used "destroy..." because it was creating multiple players on each level. Thanks once again!
No problem Sir, thank you for asking a good question, I have voted +1 :)
You do not need DontDestroyOnLoad if you use static since when you store the value in the static they won't be destroyed anyway. They actually provide an easy way to store and retrieve information and they are actually faster than a normal instance variable.
What I would recommend is to keep your script as it is but create a static class. At the end of the level before loading the next scene, transfer your values to the static class. You can then retrieve them on the other side.
Using static all the way can be "unfair". If you restart the same level, the score is kept and add each time you restart, if you use a normal variable it is set back to 0 if you reload.
See my point?