0

Can anyone explain to me, how to save "score" with PlayerPrefs and display it on the screen?

public class record : MonoBehaviour{

private Text counterText;
public float score;

void Start()
{
    counterText = GetComponent<Text>() as Text;

}

void Update()
{
    score += Time.deltaTime;
    counterText.text = "Score: " + score.ToString("00");
}}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Loper
  • 3
  • 2

2 Answers2

3

You can add 2 methods to your class

void SaveScore()
{
    PlayerPrefs.SetFloat("score", score);
}

void LoadScore()
{
    PlayerPrefs.GetFloat("score");
}

More informations about PlayerPrefs here: http://docs.unity3d.com/ScriptReference/PlayerPrefs.html

PlayerPrefs are stored in the system registry. It's not a good idea to use them to save the score, prefer a simple text file with encryption: (Stack Overflow, Unity Forum)

Community
  • 1
  • 1
RevoLab
  • 498
  • 1
  • 5
  • 8
  • "prefer a simple text file" i think it isn`t good idea, bcs player will be able to edit it :/ – Loper Jan 18 '16 at 14:39
  • Thanks for your clarification, Loper, you are right. But the system regitry is also editable with the regedit command. Altough you can easily encrypt the file/string: http://stackoverflow.com/questions/10168240/encrypting-decrypting-a-string-in-c-sharp | http://tekeye.biz/2015/encrypt-decrypt-c-sharp-string – RevoLab Jan 20 '16 at 09:18
1

PlayerPrefs utility is use to store data permanently till the app installed on device. And types supported to store is limited, such as float, int, string. You can further use it, derive new methods using int and string, its up to you.

PlayerPrefs uses Key-Value structure, that means it will store a value (int, float, string) against a string key. For example I'd save high score against the key "highscore", and by the same string key I'd get back the stored value.

Now, to save score you can use

// To set high score
int scoreToSet = 140;
PlayerPrefs.SetInt("highscore", scoreToSet);

// To get high score
int scoreToGet = 0;
scoreToGet = PlayerPrefs.GetInt("highscore");

where "highscore" is the string key. Key must match in order to get and set values.

Hamza Hasan
  • 1,368
  • 9
  • 17