- Home /
Name not saving to or loading from PlayerPrefs
Hi everyone,
I'm creating a game which includes a scoring system. The player can type their name in the input field which will hopefully save along with their score. It should then appear upon load in another scene.
However, I cannot seem to get the name to save and load, and no errors are appearing.
Here is my code:
public class PlayerName : MonoBehaviour
{
public string nameOfPlayer;
public Text inputText;
public Text loadedName;
// Start is called before the first frame update
void Start()
{
if (PlayerPrefs.HasKey("Player_Name"))
{
nameOfPlayer = PlayerPrefs.GetString("Player_Name");
}
//loadedName.text = nameOfPlayer;
}
// Update is called once per frame
void Update()
{
loadedName.text = PlayerPrefs.GetString("Player_Name");
}
public void SaveName()
{
Debug.Log("name saved");
PlayerPrefs.SetString("Player_Name", nameOfPlayer);
}
public void LoadName()
{
if (PlayerPrefs.HasKey("Player_Name"))
{
loadedName.text = nameOfPlayer;
}
else
{
Debug.Log("no name saved");
}
}
}
Currently I have submit and load buttons to save and load the name respectively. When I press the submit button, the debug log appears, but when I press load, nothing appears in the text box.
I'm not that familiar with C#, but to me it looks like I have everything I need to save and load the name. Any ideas?
Answer by rh_galaxy · Nov 18, 2020 at 05:10 AM
It's simple, you need to do a save after every time you set a key, this is to optimize if you want to set many keys at one time.
PlayerPrefs.Save();