- Home /
Save variable value.
Hi. I have script that is some kind of score system. It's working like I wanted. Now I need to save variable value after level has been unloaded and load that value after getting again into same level. But after I load level again I get value of 0. This is my script:
#pragma strict
public var buck : int;
public var ScoreBoard : GUIText;
function Start ()
{
}
function Update ()
{
if (Input.GetKeyDown("space"))
{
buck += 1;
ScoreBoard.text = ("") +buck;
}
}
Now I'm saving variable value with this code:
function setScores()
{
PlayerPrefs.SetInt("newScore", buck);
}
function getScores()
{
PlayerPrefs.GetInt("newScore");
}
And after level has been loaded again I have this code to load variable:
function OnLevelWasLoaded (level : int) {
if (level == 2)
{
ScoreBoard.text = ("") +newScore;
}
}
If I use +newScore I get error saying that there is no variable called newScore, but if I use buck variable I get value 0, as I guess it's using value from the top where variable was declared. Any way I can fix this?
Answer by perchik · Feb 28, 2014 at 05:34 PM
If you actually call setScores(), then it should register a playerpref named "newscore" with the score value.
When you want to load the new scene and get it then its just
var score: int = PlayerPrefs.GetInt("newScore");
which gets the value of playerprefs "newScore" and puts it into your new score variable.
I did that and I get same result:
public var buck : int = PlayerPrefs.GetInt("newScore");
function OnLevelWasLoaded (level : int) {
if (level == 2)
{
ScoreBoard.text = ("") +buck;
}
}
Can't do it outside of a function, you have to do that inside of a function call.
function OnLevelWasLoaded (level : int) {
if (level == 2)
{
buck = PlayerPrefs.GetInt("newScore");
ScoreBoard.text = ("") +buck;
}
}
Is this fine? Sorry, I'm not so good at program$$anonymous$$g. Also, I get this warning in console after loading this level again:
$$anonymous$$issingReferenceException: The variable ScoreBoard of 'Score' doesn't exist anymore. You probably need to reassign the ScoreBoard variable of the 'Score' script in the inspector. Score.OnLevelWasLoaded (Int32 level) (at Assets/Scripts/Level/Score.js:46)
Line 46: ScoreBoard.text = ("") +buck;
Your answer
Follow this Question
Related Questions
PlayerPrefs 2 Answers
Score and Level Loading 1 Answer
Score system Level Load 1 Answer
Problems with saving/loading score with PlayerPrefs [C#] 1 Answer