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.
1 2 3 4 5 6 7 8 9 10 11 12 |
private int score = 0; private int savedScore; void Update () { if (Input.GetKeyDown (KeyCode.S)) { PlayerPrefs.SetInt("Score", score); Debug.Log(score); } if (Input.GetKeyDown (KeyCode.L)) { savedScore = PlayerPrefs.GetInt("Score"); Debug.Log(savedScore); } |
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.
1 2 3 |
using System; using System.Runtime.Serialization.Formatters.Binary; using System.IO; |
Firstly, we need to add these 3 libraries.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
private string savedName; private int savedHealth; private string loadedName; private int loadedHealth; public void Save(){ BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/FileName.dat", FileMode.Create); PlayerClass newData = new PlayerClass(); newData.health = savedHealth; newData.name = savedName; bf.Serialize(file, newData); file.Close(); } public void Load(){ if (File.Exists(Application.persistentDataPath + "/FileName.dat")){ BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/FileName.dat", FileMode.Open); ObjData newData = (ObjData)bf.Deserialize(file); file.Close(); loadedHealth = newData.health; loadedName = newData.name; } } [Serializable] class PlayerClass{ public string name; public int health; } |
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#)
Thanks.perfect
perfeito:
Would ObjData be the name of the namespace/script?
Sorry for the wrong spelling..It would be “PlayerClass” 🙂
Thanks for the quick reply! I’ll check it once Im at my computer. I just noticed something was wrong lol
HI! tried your tutorial keep getting:
error CS0246: The type or namespace name `ObjData’ could not be found. Are you missing a using directive or an assembly reference?
Sorry, it should be “PlayerClass”
Thanks for the reply. Read the comments did not realise your supposed to change ObjData to player class.
Can you please tell us how to call these methods ?
I made the seccond method but i don’t know how to call them.
Just call them with Save(); or Load();
Thanks a lot.
Extremely helpful and straight to the point. The best tutorial for saving in Unity, it saved me a hassle. Thank you!
Bạn đang có nhu cầu vay tiền mà chẳng
thể đề xuất giúp đỡ từ bạn bè
hay người nhà . Bạn với thể tới vay
tiền banktop sẽ đáp ứng đúng lúc nhu cầu
cần vay vốn nhà băng của bạn sở hữu sản phẩm cho
vay dùng trả góp không cần tài sản bảo đảm.
Vay tiền banktop cho vay các loại vay
tiền theo bảng lương banktop, vay tiền theo cavet xe banktop, vay tin chấp
banktop, vay tiều dùng banktop. Liên hệ: 0909 023
278, 144 Cộng Hòa Phường 12 Quận Tân Bình, TP HCM
ko cần thế chấp tài sản, giấy tờ tiện lợi , tương trợ
tận nơi khách bắt buộc , Định mức vay cao nhất, giải đáp và làm cho
giấy tờ miễn phí, Hạn mức trả góp dài nhất
kiên cố sự góp sức của banktop sẽ kịp thời tương trợ cho thành công của bạn