Score value in GameOver screen is 0 instead of final value from the Game Level scene(used PlayerPrefs), how do I display the final value from Game Level scene in the GameOver scene?
I am trying to make an infinite runner, in it there are two scenes, one is game scene and the other is GameOver scene. In the game scene the score is counted live as the player moves along the z axis using the following code:
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public Transform player;
public Text ScoreValue; //means, input is required, since a variable has been created
// Update is called once per frame
void Update()
{
ScoreValue.text = ((player.position.z-15)/10).ToString("0"); //ToString("0") is to remove all decimal points
PlayerPrefs.SetString("CurrentScore", ((player.position.z-15)/10).ToString("0"));
}
}
Since this is on the Game Level scene, the score is calculated according to player movement by dragging the player object into the script. When game ends, the scene transiitions to the GameOver screen using SceneManagement. Since I want to display the score from Game Level in the Game over scene, I use a prefab to store the score.
Now in the Gameover scene I have a text object which I wanted to be updated with the final value of score form the Game Level, so i made a script for it which is as follows:
using UnityEngine;
using UnityEngine.UI;
public class GameOverScore : MonoBehaviour
{
public Text OverScore;
void Update()
{
OverScore.text = PlayerPrefs.GetFloat("CurrentScore").ToString();
}
}
Here, you have to drag the text(score value) which you want to keep updating whenever the level ends. The default score value in game over scene is set to: - Using this, the score text in Game Over scene should get updated to the final score of the game scene. But, whenever the game ends and there is a transition to the Game Over scene, the score in Game Over scene changes from: '-', to: 0. But when the level ended, the score was not 0, can someone tell me what to do or what code to use so that the value in Game Over scene is updated to final value of Game Level scene? I would really appreciate if you could help me out.
Answer by yummy81 · Apr 27, 2020 at 09:50 AM
It's simple. In your first script you set variable "CurrentScore" as string in PlayerPrefs, while in your second script you want "CurrentScore" to be returned as float. There is no variable "CurrentScore" of type float (there is a string), so that's the reason why your score is zero. So, for example you can modify your second script like that:
OverScore.text = PlayerPrefs.GetString("CurrentScore");