在 Unity 中存储和检索数据的初学者指南
Unity,让您可以创造精彩的游戏。但为了使您的游戏真正具有交互性和动态性,您需要知道如何在运行时存储和检索数据。在这个适合初学者的指南中,我们将使用易于理解的示例来探索在 Unity 中管理数据的各种方法。
为什么要在 Unity 中存储数据?
由于多种原因,在 Unity 游戏中存储数据至关重要。它允许您:
保存并加载玩家进度。
存储高分和统计数据。
管理游戏设置和配置。
跟踪游戏内物品,例如玩家库存。
创建动态且数据驱动的游戏行为。
现在,让我们深入探讨实现这些目标的一些简单方法。
- PlayerPrefs #### 玩家偏好:
PlayerPrefs 是存储和检索简单数据的最简单方法。
PlayerPrefs 将数据存储在键值对中,其中键是字符串,值只能是字符串、浮点数或整数。
这些数据保存在玩家的设备上,使其适合存储需要在游戏会话之间保留的少量信息。
PlayerPrefs 是跨平台的,这意味着它可以在 Unity 支持的多个平台上运行,例如 Windows、macOS、Android、iOS 等。
需要注意的是,PlayerPrefs 不适合存储敏感或关键数据,因为具有一定技术知识的用户可以访问和修改存储的数据。
使用方法如下:
// Storing Data:
// Save a high score
int highScore = 1000;
PlayerPrefs.SetInt(“HighScore”, highScore);
PlayerPrefs.Save();
Retrieving Data:// Load the high score
int loadedHighScore = PlayerPrefs.GetInt(“HighScore”, 0); // 0 is the default value
2. JSON : 2.JSON:
在Unity中,JSON(JavaScript Object Notation)通常用于数据序列化和反序列化。
JSON 是一种轻量级的数据交换格式,易于人类阅读和编写。
Unity 提供了对 JSON 数据处理的内置支持,可以方便地执行保存和加载游戏数据、配置文件以及与 Web 服务通信等任务。以下是在 Unity 中使用 JSON 的概述:
序列化和反序列化:
Unity 允许您轻松地将 C# 对象转换为 JSON 格式(序列化),反之亦然(反序列化)。您可以使用 JsonUtility 类来实现此目的。这是一个基本示例:
使用 JsonUtility.ToJson() 将对象序列化为 JSON 字符串。
要将 JSON 数据反序列化为 C# 对象,可以使用 JsonUtility.FromJson()。
例子 :
让我们举一个在 Unity 中使用 JSON 存储玩家得分、姓名、奖杯数和获胜状态的示例。首先,您需要创建一个 C# 类来表示玩家数据:
public class Example : MonoBehaviour {
void Start()
{
SaveData();
LoadData();
}
[System.Serializable]
public class PlayerData
{
public string playerName;
public int playerScore;
public int trophyCount;
public bool hasWon;
}
//Now, let's see how to use JSON to save and load this player data:
//Saving Player Data (Serialization)
//To save the player's data to a JSON file, you can create an instance of the PlayerData class, set its values, and then serialize it to a JSON string:
PlayerData player = new PlayerData
{
playerName = "John",
playerScore = 1000,
trophyCount = 5,
hasWon = true
};
public void SaveData()
{
string json = JsonUtility.ToJson(player);
// Save the JSON data to a file (you can replace "playerData.json" with your desired file path)
System.IO.File.WriteAllText("playerData.json", json);
}
//Loading Player Data (Deserialization)
// To load the player data from the JSON file and use it in your game, you can read the JSON data from the file, then deserialize it back into a PlayerData object:
public void LoadData()
{
string json = System.IO.File.ReadAllText("playerData.json");
PlayerData loadedPlayer = JsonUtility.FromJson<PlayerData>(json);
// Now you can access the loaded player data
string playerName = loadedPlayer.playerName;
int playerScore = loadedPlayer.playerScore;
int trophyCount = loadedPlayer.trophyCount;
bool hasWon = loadedPlayer.hasWon;
// Use the loaded data in your game
Debug.Log($"JSON Player Name: {playerName} , Score {playerScore} ,Trophy Count : {trophyCount} , Has Won : {hasWon} ");
}
}
“playerData.json”将如下所示:
{“playerName”:”John”,”playerScore”:1000,”trophyCount”:5,”hasWon”:true}
{“playerName”:“约翰”,“playerScore”:1000,“trophyCount”:5,“hasWon”:true}
在此示例中,我们创建了一个 PlayerData 类来表示玩家的信息,并使用 JsonUtility 将此数据序列化为 JSON 格式或反序列化为 JSON 格式。您可以调整此代码以在 Unity 游戏中保存和加载玩家数据。
笔记 :
JSON 是一种基于文本的格式,与二进制格式相比,机器解析成本更高,读取速度更慢,并且会使用更多内存。因此,如果您有大量数据,您可能需要考虑非基于文本的选项。
3. 可编程对象——灵活的数据容器:
Unity 中的 ScriptableObject 是一种功能强大的资源类型,允许您创建和管理自定义数据对象。以下是 ScriptableObjects 的更详细解释:
https://medium.com/p/dc0699c55b21
4. XML(可扩展标记语言):
它是一种基于文本的标记语言,设计用于存储和交换结构化数据。它使用人类可读和自我描述的格式,使人类和机器都易于理解。 XML 数据是使用标签和属性来组织的,这些标签和属性定义了数据的结构。
在 Unity 中,您可以使用 XML 来存储和交换结构化数据,例如游戏配置、关卡数据和其他设置。要在 Unity 中使用 XML,您可以使用 System.Xml 命名空间,它提供了用于读取和写入 XML 数据的类。
以下是如何使用 XML 在 Unity 中存储和检索玩家数据:
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
[Serializable]
public class PlayerData
{
public string playerName;
public int playerScore;
public int trophyCount;
public bool hasWon;
}
public class XmlSerializationExample : MonoBehaviour
{
void Start()
{
// Create a new PlayerData instance
PlayerData player = new PlayerData
{
playerName = "John",
playerScore = 1000,
trophyCount = 5,
hasWon = true
};
// Serialize the PlayerData instance to an XML file
XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
using (FileStream stream = new FileStream("playerData.xml", FileMode.Create))
{
serializer.Serialize(stream, player);
}
// Deserialize the XML data back into a PlayerData object
using (FileStream stream = new FileStream("playerData.xml", FileMode.Open))
{
PlayerData loadedPlayer = (PlayerData)serializer.Deserialize(stream);
// Now you can access the loaded player data
string playerName = loadedPlayer.playerName;
int playerScore = loadedPlayer.playerScore;
int trophyCount = loadedPlayer.trophyCount;
bool hasWon = loadedPlayer.hasWon;
// Use the loaded data in your game
Debug.Log($"XML Player Name: {playerName} , Score {playerScore} ,Trophy Count : {trophyCount} , Has Won : {hasWon} ");
}
}
}
I#### 在此示例中,我们使用 XmlSerializer 类将 PlayerData 对象序列化为 XML 文件,然后将其反序列化回 PlayerData 对象。 System.Xml 命名空间用于在 C# 中处理 XML 数据。
5. 二进制格式:
是使用二进制编码方案的数据表示,其中数据以人类不可读的形式存储。
这些格式旨在提高数据存储和传输的效率、紧凑性和速度。
与 JSON 等基于文本的格式(其中数据表示为人类可读字符)不同,二进制格式使用数值和预定义结构来编码数据。
以下是一些常见的二进制格式:
1. Protobuf 协议缓冲区:
Protocol Buffers (protobuf) 是 Google 开发的一种二进制序列化格式。与 JSON 等基于文本的格式相比,它在速度、大小和处理开销方面更加高效。以下是 protobuf 与 JSON 的比较:
Protobuf 的解析速度通常比 JSON 更快。这是因为 Protobuf 是一种二进制格式,解析二进制数据通常比解析文本数据更快、更高效。
JSON 是人类可读的,因此即使没有特定的工具也可以轻松检查和编辑。 Protobuf 是一种二进制格式,如果没有解码工具,人类就无法读取。
2. MessagePack消息包:
MessagePack 是另一种二进制序列化格式,以其简单性和高效性而闻名。它是为空间和速度而设计的。
例子 :
[MessagePackObject]
public class MyClass
{
// Key attributes take a serialization index (or string name)
// The values must be unique and versioning has to be considered as well.
[Key(0)]
public int trophyCount { get; set; }
[Key(1)]
public string playerName { get; set; }
[Key(2)]
public int playerScore { get; set; }
// All fields or properties that should not be serialized must be annotated with [IgnoreMember].
[IgnoreMember]
public string address { get; set ; }
}
void ParseData()
{
var mc = new MyClass
{
trophyCount = 10,
playerName = "santy",
playerScore = 100,
};
// Call Serialize/Deserialize, that's all.
byte[] bytes = MessagePackSerializer.Serialize(mc);
MyClass mc2 = MessagePackSerializer.Deserialize<MyClass>(bytes);
// You can dump MessagePack binary blobs to human readable json.
// Using indexed keys (as opposed to string keys) will serialize to MessagePack arrays,
// hence property names are not available.
// [10,"santy",100]
var json = MessagePackSerializer.ConvertToJson(bytes);
Console.WriteLine(json);
}
3. BinaryFormatter: 3. 二进制格式化程序:
BinaryFormatter 是 .NET Framework 中的一个类,用于以二进制格式序列化和反序列化对象。
据 Microsoft 称,BinaryFormatter 不安全且无法确保其安全。所以永远不要使用它。
希望你喜欢它。