Unity3D Local Data Persistence Record Storage

Following are several implementations of Unity local record storage.

The first Unity itself provides PlayerPrefs

// Save data

PlayerPrefs.SetString("Name",mName);
PlayerPrefs.SetInt("Age",mAge);
PlayerPrefs.SetFloat("Grade",mGrade)

// Read data

mName=PlayerPrefs.GetString("Name","DefaultValue");
mAge=PlayerPrefs.GetInt("Age",0);
mGrade=PlayerPrefs.GetFloat("Grade",0F);

// Clear all records

 PlayerPrefs.DeleteAll();

// Delete one of the records

PlayerPrefs.DeleteKey("Age");

// Write records to disk

PlayerPrefs.Save()

The second BinaryFormatter binary serialization

Suppose you have a Player class

[System. Serializable]
public class Player
{
      public int health;
      public int  power;
      public Vector3 position;
}

Because BinaryFormatter serialization does not support Unity's Vector 3 type, we need to wrap it.

public class PlayerData{
	
	public int level;
	public int health;
	public float[] position;

	public PlayerData(Player player)
	{
		this.level = player.level;
		this.health = player.health;
		this.position = new float[3];
		this.position[0] = player.transform.position.x;
		this.position[1] = player.transform.position.y;
		this.position[2] = player.transform.position.z;
	}
}

We save and read PlayerData. The read PlayerData can be assigned to Player.

public static class SaveSystem{
       //Save data
	public static void SavePlayer(Player player)
	{
		BinaryFormatter formatter = new BinaryFormatter();
		string path = Application.persistentDataPath+"/player.fun";
		FileStream stream = new FileStream(path,FileMode.Create);
		PlayerData data = new PlayerData(player);
		formatter.Serialize(stream,data);
		stream.Close();
	}

     //Read data
	public static PlayerData LoadPlayer()
	{
		string path = Application.persistentDataPath+"/player.fun";
		if(File.Exists(path))
		{
			BinaryFormatter formatter = new BinaryFormatter();
			FileStream stream = new FileStream(path,FileMode.Open);
			PlayerData data = formatter.Deserialize(stream) as PlayerData;
			stream.Close();
			return data;
		}else{
			Debug.LogError("Save file not found in  "+path);
			return null;
		}
	}
}

The third type of text file saved in json format

Use Unity's own API JsonUtility.

Save data

	public static void SavePlayerJson(Player player)
	{
		string path = Application.persistentDataPath+"/player.json";
		var content = JsonUtility.ToJson(player,true);
		File.WriteAllText(path,content);
	}

Read data

	public static PlayerData LoadPlayerJson()
	{
		string path = Application.persistentDataPath+"/player.json";
		if(File.Exists(path)){
			var content = File.ReadAllText(path);
			var playerData = JsonUtility.FromJson<PlayerData>(content);
			return playerData;
		}else{
			Debug.LogError("Save file not found in  "+path);
			return null;
		}
	}

The fourth XmlSerializer is serialized

If there are classes

public class Entity
{
    public Entity()
    {
    }
    public Entity(string c, string f)
    {
      name = c;
      school = f;
    }
    public string name;
    public string school;
}

Read data

List<Entity> entityList=null;
XmlSerializer xs = new XmlSerializer(typeof(List<Entity>));
using (StreamReader sr = new StreamReader(configPath))
{
   entityList = xs.Deserialize(sr) as List<Entity>;
}

Save data

List<Entity> entityList=null;
XmlSerializer xs = new XmlSerializer(typeof(List<Entity>));
using (StreamWriter sw = File.CreateText(configPath))
{
  xs.Serialize(sw, entityList);
}

The corresponding xml file is:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfEntity xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <Entity>
  <Name>Alice</Name>
  <School>SJTU</School>
 </Entity>
 <Entity>
  <Name>Cici</Name>
  <School>CSU</School>
 </Entity>
 <Entity>
  <Name>Zero</Name>
  <School>HIT</School>
 </Entity>
</ArrayOfEntity>

Tags: Unity JSON xml encoding

Posted on Sun, 06 Oct 2019 22:24:12 -0400 by hbsnam