question regarding saving of name and getting na score..

I developing a car adventure game… Im just wondering how to get the name of the player from the start of the scene and save it so i can the score of the player once i opened it again… any idea guys?

Use of a GUI.textfield and PlayerPrefs

Regards,
Corrupted Heart

is it ok sir if you can provide a sample code for this one? :slight_smile:

he provided you 2 links to the script ref, all the code examples you want are there.

I’m going to be honest and say that I’ve never actually dealt with PlayerPrefs however getting the username would be as simple as

var Username = "";

function OnGUI()
{
     Username = GUILayout.TextField (Username, 25);
     if(GUILayout.Button("Set Username"))
     {
             PlayerPrefs.SetString("Player Name", Username);
     }
     GUILayout.Label(PlayerPrefs.GetString("Player Name", "No Name set"));
}

I think that should work, I code in C# and I haven’t tested it but it should be correct.

Regards,
Corrupted Heart

it works sir but how can i retrieve the name that i enter to the second scene… for example i’ve finished level 1. how can i retrieve the name to level two??

At the bottom of the script I posted, I used

GUILayout.Label(PlayerPrefs.GetString("Player Name", "No Name set"));

Basically anytime that you want to use the player name you can just use,

PlayerPrefs.GetString("Player Name", "No Name set")

Regards,
Corrupted Heart

thank you sir… but another question… how can i retrieve the last 5 names who entered their names in the text field??

That would require some kind of file access, text file or xml based. I do not have experience with Unity this way so I will have to leave that to someone else to answer.

Regards,
Corrupted Heart

You can actually do this with PlayerPrefs but you need a bit of code to manage the way that the players’ name are mapped onto keys in the prefs. A convenient way is to use an array for the names and then use consecutive numbers at the ends of the keys (so you have “PlayerName1”, “PlayerName2”, etc):-

var names: String[];
var numNames: int;

function RetrieveNames() {
	for (i = 0; i < numNames; i++) {
		names[i] = PlayerPrefs.GetString("PlayerName" + i);
	}
}


function AddName(newName: String) {
	for (i = numNames - 1; i > 0; i--) {
		names[i] = names[i - 1];
	}
	
	names[0] = newName;
}


function SaveNames() {
	for (i = 0; i < numNames; i++) {
		PlayerPrefs.SetString("PlayerName" + i, names[i]);
	}
}

Use RetrieveNames to load the array before use. Then, calling AddName will push the existing names downward so that the last one falls off the list. Once you have added all the names you need to, you can then call SaveNames to store the array back in the prefs. Of course, you can go a stage further and use the retrieved names to find the users’ scores, again with PlayerPrefs.