I have a script that doesn't save the high score automatically and before I put the restart button my high score was saved without any code. I want the high score to be saved even if the player restarts the game .This is my code for the SCORE:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public int score;
public Text ScoreText;
public int highscore;
public Text highScoreText;
void Start()
{
highscore = PlayerPrefs.GetInt("HighScore: " + highscore);
}
void Update()
{
ScoreText.text = "Score: " + score;
highScoreText.text = highscore.ToString();
if (score > highscore)
{
highscore = score;
PlayerPrefs.SetInt("HighScore: ", highscore);
}
}
void OnTriggerEnter(Collider other)
{
Debug.Log("collider is working");
if (other.gameObject.tag == "Score: ")
{
score++;
}
}
}
And this is the code for the restart button:
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class RestartGame : MonoBehaviour
{
public void RestartsGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name); // loads current scene
}
}
You have problems with the keys used by PlayerPrefs
:
void Start()
{
highscore = PlayerPrefs.GetInt("HighScore");
}
void Update()
{
ScoreText.text = "Score: " + score;
highScoreText.text = highscore.ToString();
if (score > highscore)
{
highscore = score;
PlayerPrefs.SetInt("HighScore", highscore);
}
}