- Home /
Script with PlayerPrefs is not working on a different computer
Good day all,
I have a project I'm working on and I'm saving the highscore using PlayerPrefs. Everything works fine on my laptop but recently, I bought a new computer so I've decided to transfer the project there. However, the script that saves and displays the highscore doesn't work at all. I'm not sure why this is happening.
This is my script:
public class Timer : MonoBehaviour
{
public Text timerText;
public Text highscore;
public GameObject gameOverMenu;
public GameObject gameCompleteMenu;
private float startTime;
// Start is called before the first frame update
void Start()
{
startTime = Time.time;
highscore.text = "Highscore: " + PlayerPrefs.GetFloat("HighScore", 0).ToString();
}
// Update is called once per frame
void Update()
{
InputDevice device = InputDevices.GetDeviceAtXRNode(inputSource);
float t = Time.time - startTime;
string minutes = ((int)t / 60).ToString("00.##");
string seconds = (t % 60).ToString("00");
timerText.text = minutes + ":" + seconds;
if (device.IsPressed(InputHelpers.Button.MenuButton, out bool isPressed) && isPressed)
{
// setting time scale to 0 so that everything in the scene stops when ESC is pressed
if (Time.timeScale == 1)
{
Time.timeScale = 0;
}
// Debug.Log("You have quit the game");
GameFinished(); // calling the GameFinished method in order to display the high score
}
}
void GameFinished()
{
float t = Time.time - startTime;
if (t > PlayerPrefs.GetFloat("HighScore", float.MaxValue))
{
PlayerPrefs.SetFloat("HighScore", t);
highscore.text = "Highscore: " + t.ToString("00") + " seconds";
PlayerPrefs.Save();
}
}
What could be the issue? I'm not getting any errors or anything at runtime either so I'm kinda stuck.
you have not explained why it doesnt work and what happens
Well I wouldn't be uploading this question if I knew why it doesn't work. :) In my game there's a timer, and I save and display the highscore of this timer whenever the player ends the game (how long has the player spent their time in this level). Everything works fine on my laptop, but when I moved the project to my new computer this script just stopped working. No error, nothing. It doesn't save the highscore nor display it. It just looks "0" when I end the game.
Answer by xxmariofer · Jun 03, 2021 at 10:26 AM
your issue is in this line
if (t > PlayerPrefs.GetFloat("HighScore", float.MaxValue))
if most likely playerprefs doesnt have any value, so it gets the default value of maxvalue, so "t" will never be higher than maxValue and "HighScore" key will never change its value
just do a comprobation
void Awake()
{
if(PlayerPrefs.GetFloat("HighScore", -1) == -1)
{
PlayerPrefs.SetFloat("HighScore", 0);
}
}