- Home /
Creating a Playerpref score system
I am brand new to Unity. Up to this point I have been using tutorials to help get my first game to where it is. I have looked through documentation, the forums and Youtube to find a beginning or solution to what I'm trying to do. What im attempting is a system where every second it gives you a set ammount of points. Every set ammount of points it gives you a coin. But everytime it updates you're points it updates the Score UI Text. I can't figure this out. I also can't figure out how to do a PlayerPref IF. Here is my code.
public Text scoreText; public Text highScoreText;
public int pointsPerSecond;
public int coinsPerPoints;
public int score;
public int matchCoins;
// Use this for initialization
void Start () {
PlayerPrefs.GetInt("HighScore");
score = 0;
matchCoins = 0;
}
// Update is called once per frame
void Update () {
}
//THIS IS THE END OF CODE IN THIS FORUM POST
My idea is having an if that says if the Playerpref highscore is less then score after the bool "dead" Is activated in the player it updates the Highscore to be score. I know how to do that. But not how to access the Bool from my Player script. Or to set up Courotines or anything of the sort. And the Unity time system all around confuses me. Help here would be appreciated.
I also want to do where every 10 seconds it gives the player 5 coins. So all this goes over my head a bit.
Answer by Larry-Dietz · Dec 28, 2017 at 05:37 AM
Try something like this. It is untested, but I think it will do basically what you are wanting...
public Text MyTextDisplay;
public Player MyPlayer;
public int pointsPerSecond;
public int coinsPerPoints;
private int _score;
public int score {
get{return _score;}
set {
_score=value;
MyTextDisplay.text = _score.ToString();
}
}
public int matchCoins;
private float PointTimer=0;
private float CoinTimer=0;
private bool GameOver=false;
// Use this for initialization
void Start () {
score = 0;
matchCoins = 0;
}
// Update is called once per frame
void Update () {
if(GameOver)
return;
if (!MyPlayer.Dead) {
PointTimer+=Time.deltaTime;
if (PointTimer>1){
PointTimer=0;
Score+=pointsPerSecond;
}
CoinTimer+=Time.deltaTime;
if (CoinTimer>10){
CoinTimer=0;
matchCoins+=5;
}
} else {
int HighScore = PlayerPrefs.GetInt("HighScore",0);
if (Score>HighScore)
PlayerPrefs.SetInt("HighScore", Score);
}
}
Again, this is untested, I just wrote it here in the response directly, but short of a typo, I think it will do what you are looking for. Just drag the Player and Text objects into the appropriate fields in the inspector.
Hope this helps, -Larry
You are welcome. Glad I could help. If you could, mark the answer as accepted :)
-Larry
I always forget to do that. Sorry