Game Development Reference
In-Depth Information
Next, we set up the necessary parameters for this class. Then, we save the score in the
SaveLocal(index : int)
funcion, which will take the
index
number of each user
included with the local key and put in the
PlayerPrefs
key. This will allow us to save
muliple users without having any problems.
In the
SaveLocal()
funcion, we use
PlayerPrefs.SetInt(KeyString, int_
score);
to save the score and
PlayerPrefs.SetString(KeyString, s_name);
to
save the username.
Next, we have the
LoadLocal(index : int)
funcion, which will take the index number
of the users and load the username and score from the
PlayerPrefs
.
The
LoadLocal()
funcion will contain two funcions. The irst is
LoadScore(index
: int)
, which will load the user's score by using
PlayerPrefs.HasKey(KeyString)
to check for the similar key saved on this local machine. If it has, we will load the score
by using the
PlayerPrefs.GetInt(KeyString)
funcion, and if not, we will return
0
for the score. The next funcion is
LoadName(index : int)
, which is very similar
to the
LoadScore(index : int)
funcion, but this ime we will use
PlayerPrefs.
GetString(KeyString)
to get the username. Also, if we can't find the key, we will return
the random name in the
as_randomNames
array of string.
Then, we created the
LocalHiScore
script to load and save our user data. In this script, we
created
SetMaxUser(maxUser : int)
to get the maximum number of users to display on
the menu, and called the
LoadGameLocal()
funcion. This funcion will load the user data,
and then store the data to the array. The funcion also gets the minimum score from the user
data and stores this score for comparing when the player submits the score.
In the
LocalHiScore
script, we also created
SaveGame
(scores
:
int,
name
:
String)
to save the player's final score to the local machine and the
SortUser
(array
:
UsersData[])
funcion to sort the user data before saving. In the
SaveGame
(scores :
int, _name : String)
funcion, irst we checked whether the player's submited score
is higher than the minimum score from the user data or not. If it isn't, we don't add the new
score to the user data. On the other hand, if the submited score is higher than the minimum
score, the old minimum score will be removed, and the new score will be added to the new
user data. Then, we call the
SortUser (array : UsersData[])
funcion. This funcion
will sort the array of the
UsersData
from the highest to lowest user score.
Finally, we go back to the
HiScore
script to add the script that will display our local
high score.