Hey, i've got some trouble as im trying to display a Playerpref string in a gui textfield, heres the code:
var name1 : String = PlayerPrefs.GetString("Player1 Name");
var namevar1 : String;
function OnGUI () {
GUI.Box (Rect (10, 40,500,500), "");
GUI.Label (Rect (20, 50,100,20), "Spelare #1 - ");
namevar1 = GUI.TextField (Rect (90, 50,100,20), ""+name1);
PlayerPrefs.SetString("Player1 Name", namevar1);
//player1lvl = GUI.TextField (Rect (195, 50,100,20), ""+player1lvl);
//PlayerPrefs.SetString("Player1 Level", player1lvl);
//p1use = GUI.TextField (Rect (300, 50,15,20), ""+p1use);
//PlayerPrefs.SetString("Player1 Use", p1use);
}
Made lines that ain't relevant right now comments. Thanks in advance!
Current code:
var playerName : String;
function OnEnable() {
playerName = PlayerPrefs.GetString("Player1 Name", "Player 1");
}
function OnDisable() {
PlayerPrefs.SetString("Player1 Name", playerName);
}
function OnGUI () {
if (GUI.Button (Rect (10,10,100,20), "Instllningar"))
showMoreGui = true;
if (showMoreGui) {
GUI.Box (Rect (10, 40,500,500), "");
GUI.Label (Rect (20, 50, 100, 20), "Spelare #1 - ");
playerName = GUI.TextField (Rect (90, 50, 100, 20), playerName);
if (GUI.Button (Rect (400, 510,100,20), "Stng"))
showMoreGui = false;
}
}
The second variable "Player 1" is the default value returned if there was no value to start with. For example, playing the game for the first time. It's just a convenience so you don't have to write code such as if !exists player1, set player1 "Player 1". If you are going to repeat input like that I'd suggest you make a function that handles this automatically. Store each player value in a new class for easier variable management.
– StatementI suggest you make helper functions like LabelTextField which accept two parameters (except rect). Like so: LabelTextField(Rect (10, 40, 500, 500), "Spelare #1", player1.name);
– StatementAnd also make a higher level function like PlayerGUI(Rect(.....), player1) which in turn make use of LabelTextField, which you also have to code for yourself. Much cleaner than having a ton of controls right after each other :)
– StatementTo group gui items make use of GUI.BeginGroup and GUI.EndGroup. That way you can work with relative position. There's also GUILayout so you don't have to deal a lot with rect sizes. Either way works of course and as long you get the job done any way is the right way :)
– StatementIt won't save to player prefs until the script is disabled (OnDisable, right?). You could have a save button (or save it when user closes that window) in your gui code. But try not to save it every OnGUI call because it's just a waste.
– Statement