- Home /
How to name a player
I'm making a Earthbound fan game, and i'm having trouble naming the charterers he's my code using UnityEngine; using UnityEngine.SceneManagement;
public class Askname : MonoBehaviour
{
private new string name;
[SerializeField] private string Stl;
public AudioClip SoundToPlay;
private new readonly AudioSource audio;
void OnGUI()
{
name = GUI.TextField(new Rect(10, 10, 200, 50), name);
if (Input.GetKey(KeyCode.KeypadEnter))
{
NextScene();
}
}
void NextScene()
{
audio.PlayOneShot(SoundToPlay);
SceneManager.LoadScene(Stl);
}
}
It would really help if could answer this thank you if you do.
What are you doing with the name property after you set it from the GUI textfield? It goes nowhere, it's just garbage collected?
Answer by metalted · Mar 16, 2020 at 04:01 PM
First of all, like @ShadyProductions mentions, you are not actually doing anything with the data that is provided by the GUI.Textfield. So its not really a case of "having trouble" its more like not doing anything. The value will not magically appear somewhere in a script because you made a textfield. The value needs to be assigned to something, maybe a gameobject, maybe a file that doesn't get reloaded while changing scene.
So to make it work: assign the value to something useful and create/use a script that can transfer data from one scene to another, otherwise the data is lost anyway.
The name = GUI.TextField doesn't work if so why not?
Im not really sure what you mean with this question. If you are saying that the "name = GUI.TextField" isn't working and why that is, the only guess i have is because of the "new" keyword. I dont think this will cause any trouble but im guessing it is there because Visual Studio told you to put it here because of intended hiding of the variable . What you could try is to remove the new keyword from the name variable, and use another variable name, one that will reflect what the variable holds, like : playerName.
That fixed it, but that caused a new problem it won't load the scene.