Save and Load Game – Unity3D (C#)


Save and Load Game – Unity3D (C#)

People thinks that save and load functions are a little bit complicated in game development. We will use 2 types of game saving and game loading in Unity3D and you will get that it is not as complex as you think. We use PleyerPrefs and persistentDataPath.

 

Using PlayerPrefs:

You can save and load 3 types of variables: int, float and string. If you want to save or load player name, score, time etc., PlayerPrefs is the easiest way. Just give a name and a  value across it. Lets try to save and load player score. It is compitable with web player.

In code above, we save score as Score with PlayerPrefs.SetInt function. We load Score and assign it to savedScore with PlayerPrefs.GetInt function. Now, when you press play, it saves score with S key and loades score with L key. Every time you save and load, you can see saved and loaded score in console with Debug.Log function.

 

Using persistentDataPath:

In this section, we work with I/O files. We can use multiple values with persistentDataPath. For example, create a Player class with health and name. we will save and load these values.

Firstly, we need to add these 3 libraries.

In this code, we create a file named FileName.dat and we save our class data. You need to add [Serializable] before your class.

As I said, you can save int, float and string type values. That doesn’t mean you can’t save color, position etc. If your player position is Vector3, you can save it with float values such as position.x, position.y, position.z. Also you can save color with its name and call it in load with name.

 

©Coffee Break Codes – Save and Load Game – Unity3D (C#)


Leave a comment

Your email address will not be published. Required fields are marked *

12 thoughts on “Save and Load Game – Unity3D (C#)