How do I access playerprefs from another script?
Not sure if that was the right wording for this question but hopefully you guys understand. I'm trying to save my score value in game so that I can display it on the death screen. Thanks in advance!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
int scriptScore = 0;
public Text score;
int timeUntil = 5;
public static int Otherscore;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (PlayerDeath.isAlive == true)
{
score.text = "Score: " + scriptScore;
timeUntil--;
}
if(timeUntil == 0)
{
scriptScore++;
timeUntil = 5;
}
Otherscore = scriptScore;
}
}
That's the script for the score in game. And below is my attempt at displaying it on the death screen.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class HighScore : MonoBehaviour
{
public TextMeshProUGUI highScore;
void Start()
{
highScore.text = PlayerPrefs.GetInt("HighScore", 0).ToString();
}
public void displayScore()
{
if(Score.Otherscore > PlayerPrefs.GetInt("HighScore", 0))
{
PlayerPrefs.SetInt("HighScore", Score.Otherscore);
highScore.text = Score.Otherscore.ToString();
}
}
}
Answer by Mouton · Sep 29, 2019 at 11:31 AM
As I don't know your game logic, I can only make asumption but I think your HighScore and Score components are not called from the same Scene OtherScore
is then set to 0 since a new scene have been loaded and every objects destroyed.
However, for many reasons, using a static is not the good approach. You should instead write the HighScore
PlayerPref when the game stops instead of when you display scores.
public class Score : MonoBehaviour
{
// ...
private void Update()
{
if (PlayerDeath.isAlive == true)
{
// ...
}
else
{
EndGame();
}
}
private void EndGame()
{
int currentScore = scriptScore; // Mandatory, I don't like the actual name
int maxScore = PlayerPrefs.GetInt("HighScore", 0);
if (currenttScore > maxScore)
{
PlayerPrefs.SetInt("HighScore", currentScore);
}
}
}
Then, in your HighScore class, you can just write the current score.
public class HighScore : MonoBehaviour
{
public TextMeshProUGUI highscore;
public void displayScore()
{
highScore.text = PlayerPrefs.GetInt("HighScore", 0);
}
}
Thanks for this solution! I ended up figuring it out on my own and the high score wasn't saving because I defined it in the start function, simple yet destructive mistake. Your response is also a great solutions. So again I thank you.