- Home /
Save score in Unity
I have the following script which I use for calculating the score
public class Score : MonoBehaviour {
Score sc;
void Start()
{
GameObject obj = GameObject.Find("ScoreSystem");
sc = obj.GetComponent<Score>();
}
void OnTriggerEnter2D(Collider2D coll)
{
if (coll.tag == "Ball")
{
sc.score++;
}
} }
and this is the class where I increase the value
public class Score : MonoBehaviour {
public int score;
void Start()
{
score = 0;
}
}
But the problem I have is that the value always stays 0 when I switch to a different scene. I even used this code to store the value and display in the next scene but it didn't work
void Update()
{
PlayerPrefs.SetInt("score", score);
PlayerPrefs.Save();
}
and this code for taking the value
score = PlayerPrefs.GetInt("score");
How can I store the latest value inside an Int and display it in the next scene and when I leave that scene it reverts back to 0?
Answer by SohailBukhari · Jul 14, 2017 at 12:09 PM
first your score calculating script and the script where you are increasing value have the same name. change the class name as ScoreSystem
and then update value. you have to update your prefs
in the OnTriggerEnter2D
method instead of update.
void OnTriggerEnter2D(Collider2D coll)
{
if (coll.tag == "Ball")
{
sc.score++;
PlayerPrefs.SetInt("score", sc.score);
PlayerPrefs.Save();
}
}
and make sure your OnTriggerEnter2D
method is working fine. Note:
you can get PlayerPrefs
as you set in the code.
Your answer
Follow this Question
Related Questions
Highscore won't save 3 Answers
How can i save a variable for only one scene? 1 Answer
Playerprefs to save unlocked button 2 Answers
save unlocked character by Playerprefs 3 Answers
How to save color 3 Answers