Set the username with an inputfield ?
Hi guys, i'm new around unity/c#, and i'm trying to make an online leaderboard for a flappy bird like game,i followed Sebastian Lague's Dreamlo tutorial,and from the looks of it, i need a username,and can't quite figure it how to do it.I put an InputField in the main menu, but it doesn't save it at all. (No completions found for Player prefs) Any help would be awesome. Thanks! This is my wanna be code for that:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class InputName : MonoBehaviour {
public string userName;
public GameObject inputField;
public void Awake()
{
userName = inputField.GetComponent<InputField> ().text;
}
}
Answer by UnityCoach · Mar 30, 2017 at 11:37 AM
Hi, first you need a public method that takes a string for parameter
public class InputName : MonoBehaviour
{
public string userName;
public void SetUserName (string text)
{
userName = text;
}
}
Then, in the editor, add an action to the OnValueChanged event of the Inputfield to point to that method.
You can also save/reload it with PlayerPrefs, like :
public class InputName : $$anonymous$$onoBehaviour
{
public string userName;
public InputField inputField;
public void Awake()
{
userName = PlayerPrefs.GetString ("playerName", "Player");
inputField.text = userName;
}
public void SetUserName (string text)
{
userName = text;
PlayerPrefs.SetString ("playerName", userName);
}
}
And for the sake of code awesomeness, I would use a property/accessor.
public class InputName : $$anonymous$$onoBehaviour
{
public InputField inputField;
private string _userName
public string userName
{
get
{
if (_userName == string.Empty)
_userName = PlayerPrefs.GetString ("playerName", "Player");
return _userName;
}
set
{
_userName = value;
PlayerPrefs.SetString ("playerName", _userName);
}
}
public void Awake()
{
inputField.text = userName;
}
public void SetUserName (string text)
{
userName = text;
}
}
I'm happy to help. If it all works, please accept the answer so that it closes the question. If you'd like more tips, you can subscribe to my youtube page, or check out my full training course
Answer by designerpro11 · Apr 08, 2021 at 12:22 AM
How to Display Text from InputField and Save User name in Unity https://youtu.be/uoLk9iBTnls