What am I doing wrong with PlayerPrefs?

I have been trying for days now to get my game to locally save the High Score. I have read just about every post, and watched numerous videos on the subject. I still cannot get this to work. Here is the C# code I am using:

using UnityEngine;
using System.Collections;

public class ScoreManager : MonoBehaviour {

	public static int highScore = PlayerPrefs.GetInt ("HighScore", 0);

	void AddScore() {


		int score = Destroyer.score;

				if (score > highScore)
						highScore = score;
						PlayerPrefs.SetInt ("HighScore", score);
		}
}

I have it collecting the current score from this script, which works just fine keeping the current score:

using UnityEngine;
using System.Collections;
public class Destroyer : MonoBehaviour {

	public static int score = 0;

	void OnTriggerEnter2D (Collider2D other){
		score = score + 1;
		Destroy (other.gameObject);
	}
	
		void Start(){
			
	}
}

Like I said, I don’t know why this doesn’t work. From everything I have read, it should. What am I doing wrong, and where is the best place to run this code?

Hard to say if this is the only problem since “doesn’t work” is not a lot of info but at leadt you are writing the score to prefs every time regardless of whether it’s bigger or smaller than the old score.

if (score > highScore)
   highScore = score;
   PlayerPrefs.SetInt ("HighScore", score);

Because you are not using curly brackets, the effective range of the if-block is until the first semicolon after it.

Okay…I got it to work. I ended up just moving the code to the same code that keeps the current score. Here it is:

using UnityEngine;
using System.Collections;
public class Destroyer : MonoBehaviour {

	public static int score = 0;
	public static int highScore = PlayerPrefs.GetInt ("HighScore", 0);

	void OnTriggerEnter2D (Collider2D other){
		score = score + 1;
		if (score > highScore) {
			PlayerPrefs.SetInt ("HighScore", score);
			Debug.Log ("HighScoreSet");
		}
		Destroy (other.gameObject);
	}
	
		void Start(){

	}
}

Then to display the high score in game I used this code:

void Update () {
		guiText.text = "HIGH SCORE : " + PlayerPrefs.GetInt ("HighScore");
	}

Eventually I am going to have a high score for each difficulty (easy, medium, hard). When I figure out how to do that, I will post that code as well.

Have you ever considered saving the data to playerprefs at all.

I mean your codes are great, but in no part of your code, the PlayerPrefs.Save() method is called to save datas.


// Saves data to playerprefs permanently
PlayerPrefs.Save();

Note: You wont need this if you only want data for temporary usage, otherwise I can’t say!!