Game Development Reference
In-Depth Information
Objective complete - mini debriefing
In this step, we basically created
LocalHiscore
to save and load the user's local high-
score data and displayed it on the
LOCAL HI-SCORE
page. The
LocalHiscore
class
is derived from the
Hiscore
class, which we already created. In this class, we added the
Initialize()
,
LoadUserData()
, and
SaveUserData()
methods, which is over-
ridden from the
Hiscore
base class. Using the
virtual
and
override
keywords, we
will be able to share the method and variables from the
Hiscore
class.
In the
SaveUserData()
function, we first passed the user data that we'd like to save.
Then, we added the user data to the list of
UserData
, which is
_users.Add(user);
.
Next, we created
BinaryFormatter
and
MemoryStream
to serialize the list of
UserData
to the series of bits to the memory buffer using
bin-
ary.Serialize(memory, _users);
. Next, we used
PlayerPrefs
to save the
data by first converting the string using
Con-
vert.ToBase64String(memory.GetBuffer());
. Then, we used
Player-
Prefs.SetString()
to set the data by passing the key, which is
_hashkey +
"Highscore"
, and the converting string data.
Note
We need to convert our data to a string first. This is because
PlayerPrefs
can only save
string
,
int
, or
float
and not the bytes array. We can check the following link for
Next, we created
Initialize()
and
LoadUserData()
to set up and load the default
user data if there is no local user data. In the first line, we called
base.Initialize()
(for C# users) and
super.Initialize()
(for Unity JavaScript users). This basically
calls the
Initialize()
method from the base class, which is the
Hiscore
class to set
the maximum users that should be shown on the high-score table.
In the
LoadUserData()
method, we first checked whether the local user data exists or
not using
string data = Player-
Prefs.GetString(_hashkey+"Highscore", "");
. Then, we checked to see
whether the return string isn't equal to an empty string. We converted it back to the memory
buffer and deserialized it to the list of
UserData
. On the other hand, if the data was an