The scoring of my game is based on how far the player travels on the x-axis. I use this code to calculate it:
public Transform player;
public Text scoreText;
void Update()
{
scoreText.text = player.position.x.ToString("0");
}
After the player collides with an object, they are sent to the Game Over scene. The problem is, I am not able to/ I don’t know how to display the final score when they lose. I have tried using DontDestroyOnLoad and PlayerPrefs, but I couldn’t get either of them to work with UI Text.
Why don’t you just store the text string and than set the next scene’s UI text.text to that string
Method 1:
// Old scene
string score = player.position.x.ToString("0");
PlayerPrefs.SetString("score", score);
// New scene
newScoreText.text = PlayerPrefs.GetString("score");
Method 2:
// Static variables are not stored in script instance, they are stored in stack, that means they are "remembered" even on scene change
// Scene is just used to get name of current scene
using UnityEngine.SceneManagement;
private string sceneName;
public static string score = player.position.x.ToString("0");
private void Start() {
sceneName = SceneManager.GetActiveScene().name;
if (sceneName == "GameOverScene") {
newScoreText.text = score;
}
}