I have a function i wrote for keeping track of a players high score between games. It works perfect on the PC ( when I hit play in unity editor) however It will not work on my android device.
Any Idea?
void SetHighscore(int myscore)
{
string key = "highscore";
bool haskey = PlayerPrefs.HasKey (key);
int highscore=0;
if (haskey) {
highscore=PlayerPrefs.GetInt (key);
if (highscore < myscore) {
PlayerPrefs.SetInt (key, myscore);
highscore=myscore;
PlayerPrefs.Save();
}
}
HighScoreMesh.text = "High Score: "+highscore.ToString();
}
What it should do on first high score when PlayerPrefs is empty?
says that PlayerPrefs.GetInt (key) returns the “default value”
My understanding was that the default value for int was 0, is that not the case ?
I mean
bool haskey = PlayerPrefs.HasKey (key);
int highscore=0;
if (haskey) {
that part.
I don’t know how I over looked that… I don’t know why the script worked on PC without the else condition, Thank you.
Solution used in a different project :
if (haskey) {
highscore = PlayerPrefs.GetInt (key);
if (highscore < myscore) {
PlayerPrefs.SetInt (key, myscore);
highscore = myscore;
score=myscore;
PlayerPrefs.Save ();
}
score=highscore;
} else {
PlayerPrefs.SetInt (key, 0);
}
This bugged me a lot - I thought Android was too slow with the loading process and somehow that was the issue. Instead it was exactly as you posted above; on Android (contrary to PC) you have to check with HasKey() first.
I have a function i wrote for keeping track of a players high score between games. It works perfect on the PC ( when I hit play in unity editor) however It will not work on my android device.
same proble
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreManager : MonoBehaviour {
public Text scoreText;
public Text highScoreText;
public float scoreCount;
public float highScoreCount;
public float pointsPerSecond;
public bool scoreIncreasing;
public bool shouldDouble;
// Use this for initialization
void Start () {
if (PlayerPrefs.HasKey(“HighScore”))
{
highScoreCount = PlayerPrefs.GetFloat(“HighScore”);
}
}
// Update is called once per frame
void Update () {
if (scoreIncreasing)
{
scoreCount += pointsPerSecond * Time.deltaTime;
}
if (scoreCount > highScoreCount)
{
highScoreCount = scoreCount ;
PlayerPrefs.SetFloat(“HighScore”, highScoreCount);
}
scoreText.text = "Score: " + Mathf.Round (scoreCount);
highScoreText.text = "High Score: " + Mathf.Round (highScoreCount);
}
public void AddScore(int pointToAdd)
{
if (shouldDouble)
{
pointToAdd = pointToAdd * 2;
}
scoreCount += pointToAdd;
}
}