The question is answered, right answer was accepted
Problem with PlayerPrefs
I got a simple script, where player is typing his nickname in Input Field, than press Enter (Return) and script must save the nickname through the PlayerPrefs function. And after that every time Player returns to the main scene, script must put text back in Input Field to edit nickname. But it doesn't work as I want. Can someone help me with it?
public class NicknameScript : MonoBehaviour
{
public Text textNickname;
private void Start()
{
textNickname.text = PlayerPrefs.GetString("Nickname");
Debug.Log(textNickname.text);
}
void Update()
{
gameObject.GetComponent<Text>().text = "Welcome back, " + textNickname.text + "!";
if (Input.GetKey(KeyCode.Return))
{
PlayerPrefs.SetString("Nickname", textNickname.text);
}
}
}
Answer by KevRev · May 04, 2019 at 09:12 AM
Try the following:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class NickNameScript : MonoBehaviour
{
public InputField iField;
public string myName;
private void Start()
{
if (PlayerPrefs.GetString("Nickname")!="")
{
iField.text=PlayerPrefs.GetString("Nickname");
myName=iField.text;
}
updateWelcome();
}
void Start()
{
if (Input.GetKey(KeyCode.Return)) refreshWelcome();
}
public void updateWelcome()
{
myName = iField.text;
if (myName != "")
{
Debug.Log("Welcome back " + myName);
PlayerPrefs.SetString("Nickname", myName);
}
else
{
Debug.Log("Welcome Guest.");
}
}
}
In the Editor, add an InputField component to the text box. Add a condition to run the updateWelcome() method when the Input Field changes.
This should now update either when the Input Field changes or you press Enter (only added so you could see how to grab that, but the OnChange makes it redundant in this example).
Thanks, it works. But you made some mistakes in your code. After changing it a little bit, it finally works!
Excellent, glad it helped. I'm typing on my mobile with no debugger and contending with autocorrect lol sorry.
Follow this Question
Related Questions
Add "1" to score text? Not "11111"? 1 Answer
Countdown Timer 2 Answers
How can I load sprite from previous scene? 1 Answer
Problem with saving player data 0 Answers
Get single component from canvas, instead of all components 1 Answer