- Home /
How do you transfer UI Text from one scene to another?
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.
Can someone help me?
You're not really clear on what you wanted to keep and how you tried to do it. DontDestroyOnLoad is the right thing to keep gameobjects between scenes and PlayerPrefs is a valid way to transfer data. Since neither of the ways described are shown in your code nor do you explain how exactly you tried to use them, it's hard to help.
Answer by leSamo · Jan 02, 2018 at 08:41 PM
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;
}
}
Thanks for the reply!
The issue with $$anonymous$$ethod 1 is that when I store the value as a string, the text in the game doesn't update with the player movement which makes the newScoreText value incorrect.
The issue with $$anonymous$$ethod 2 is that when I type line, public static string score = player.position.x.ToString("0"); I get the error "a field initializer cannot reference the nonstatic field..." underlining "player".
If you could figure out how to fix either method, it would be greatly appreciated :D
Your answer
Follow this Question
Related Questions
Multiple EvenetSystems in Scene - only have 1 after searching though 1 Answer
When die - reset score from the last scene 2 Answers
How to get rid of the duplicates created by DontDestroyOnLoad? 3 Answers
One PlayerPref not saving 1 Answer
Worldspace UI in wrong position/scale after scene change 0 Answers