Unity PlayerPrefs、JsonUtility

There are two commonly used data storage methods in Unity: PlayerPrefs and JsonUtility.

  1. PlayerPrefs

PlayerPrefs is a lightweight data storage method built into Unity, which can be used to store a small amount of game data, such as scores, unlock status, etc. When using PlayerPrefs, you need to pay attention to the following points:

  • When storing data, you need to use strings as keys (key) and values ​​(value).
  • The stored value can only be int, float, and string. If you need to store other types of data, you need to perform type conversion.
  • After storing the data, you need to call the Save method to save the data locally.

Here is an example of storing and reading data using PlayerPrefs:

// 存储数据
PlayerPrefs.SetInt("Score", 100);
PlayerPrefs.SetString("UserName", "John");
PlayerPrefs.Save();

// 读取数据
int score = PlayerPrefs.GetInt("Score");
string userName = PlayerPrefs.GetString("UserName");
  1. JsonUtility

JsonUtility is a built-in tool for serializing and deserializing Json data in Unity, which can be used to store and read complex game data, such as game settings, archives, etc. The following points need to be paid attention to when using JsonUtility:

  • When storing data, the data needs to be serialized into a string in Json format.
  • When deserializing data, you need to deserialize the string in Json format into the corresponding data structure.
  • Since JsonUtility only supports some basic data types (such as int, float, string, etc.) and some built-in data structures (such as arrays, dictionaries, etc.), if you need to store custom data structures, you need to perform corresponding conversions.

Here is an example of storing and reading data using JsonUtility:

// 定义数据结构
[System.Serializable]
public class PlayerData
{
public int score;
public string userName;
public float[] position;
}

// 存储数据
PlayerData data = new PlayerData();
data.score = 100;
data.userName = "John";
data.position = new float[] { 1.0f, 2.0f, 3.0f };
string json = JsonUtility.ToJson(data);
File.WriteAllText(Application.dataPath + "/playerData.json", json);

// 读取数据
string jsonString = File.ReadAllText(Application.dataPath + "/playerData.json");
PlayerData loadedData = JsonUtility.FromJson<PlayerData>(jsonString);
int score = loadedData.score;
string userName = loadedData.userName;
float[] position = loadedData.position;

Note: When using JsonUtility to store and read data, it is necessary to convert the data into a string in Json format and save it in a local file, so attention should be paid to the security and integrity of the data.

Guess you like

Origin blog.csdn.net/qq_60125117/article/details/130426754