This is a simple C# script example for a C# class Player.
The class Player come with this content into Player.cs C# script:
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 | using UnityEngine; using System.Collections; public class Player : MonoBehaviour { public int level = 1; public int energy = 100; public int health = 100; public int attack = 5; public int defense = 2; //make Save and Load public void Save() { SaveLoadManager.SavePlayer(this); } public void Load() { int[] loadStat = SaveLoadManager.LoadPlayer(); level = loadStat[0]; energy = loadStat[1]; health = loadStat[2]; attack = loadStat[3]; defense = loadStat[4]; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } } |
To make this C# script for saving the Player into one file I used this C# script named SaveLoadManager.cs:
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | using UnityEngine; using System; using System.Collections; using System.Runtime.Serialization.Formatters.Binary; using System.IO; public static class SaveLoadManager { public static void SavePlayer(Player player) { //create binary file BinaryFormatter bf = new BinaryFormatter(); FileStream stream = new FileStream(Application.persistentDataPath+"/player.sav",FileMode.Create); //this will use the class PlayerData PlayerData data = new PlayerData(player); //use Serialize - bf.Serialize(stream, data); //close file stream stream.Close(); } //load the file public static int[] LoadPlayer() { //check the file exist if (File.Exists(Application.persistentDataPath + "/player.sav")) { //open binary file BinaryFormatter bf = new BinaryFormatter(); FileStream stream = new FileStream(Application.persistentDataPath + "/player.sav", FileMode.Open); PlayerData data = bf.Deserialize(stream) as PlayerData; //close file stream stream.Close(); //return data from file return data.stats; } else { Debug.LogError("File don't exist!"); return new int[5]; } } } // need to use using System; to use Serializable area. [Serializable] public class PlayerData { // more convenient for us to store data public int[] stats; public PlayerData(Player player) { stats = new int[5]; stats[0] = player.level; stats[1] = player.energy; stats[2] = player.health; stats[3] = player.attack; stats[4] = player.defense; } } |
The script come with two parts for save and load files.
I used Serializable property to save a binary file named player.sav.
This script used also the Application.persistentDataPath to take the path of the application.
I used a Debug log output but if you want to use into the real application then is no need to use.
You can deal with any player settings and make new like player.magic or player.status.
Take a look at the comments in the script and that script highlights design issues.