- Home /
How can i link a static string variable to another scene and display it?
Hi all, I am just starting to learn how to use Unity to create a simple 2D game, and i have encountered a issue. I try to search through forums and also follow the Unity tutorial https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial/displaying-score-and-text step by step but to no avail.
My issue is that , in one scene i use input field to let user key in name (string) and save them, using the script below:
public class SetPlayerName : MonoBehaviour
{
public InputField usernameInput;
public static string playername;
void Start()
{
if (playername != null)
usernameInput.text = playername;
}
public void SaveUsername(string newName)
{
playername = newName;
SceneManager.LoadScene("ChooseCharacterScene");
}
// Update is called once per frame
void Update () {
}
}
So that the name is saved into a static variable called playername.
Now in my next scene, I want to display the name. What I did is create a UI text in canvas. Create a game object that store the following script:
public class DisplayName : MonoBehaviour {
public Text p1name;
// Use this for initialization
void Start () {
p1name.text = SetPlayerName.playername;
}
// Update is called once per frame
void Update () {
}
}
and just pull the UI text element icon put into the script just like this: PlayerName is my ui text element name
What happens is that when playing the scene it does not display anything. However if i change my p1name.text = "Hello", it does display the correct string.
Is it because the way i import the static variable is incorrect thus it is not displaying on canvas?
Please forgive me if i asking a noob or amateur question. Welcome all the replies and help!
Answer by FFXVignis · Oct 27, 2018 at 06:34 PM
Nevermind i have make it worked! I have done some major changes by referring to https://forum.unity.com/threads/passing-inputfield-text-to-next-scene.490505/
Thank you all!