unity保存游戏数据
In this tutorial, we’ll learn to implement Save/Load game functionality in our game. We will begin by saving the necessary player-related data such as the level we’re on, where we are, and our example tutorial statistics.
在本教程中,我们将学习在游戏中实现“保存/加载”游戏功能。 我们将首先保存与玩家相关的必要数据,例如我们所处的级别,所在的位置以及示例教程统计信息。
If you need a project for testing, you can use the one at the end of the previous article which dealt with cross-scene saving of data, and it’s perfect for following this tutorial:
如果您需要一个项目进行测试,则可以使用上一篇文章结尾处的一个项目,该项目涉及跨场景的数据保存,它是遵循本教程的理想选择:
下载 (Download)
Saving Data Between Scenes in Unity – previous article [GitHub Repository] [ZIP Download]
在Unity中的场景之间保存数据–上一篇文章 [GitHub存储库] [ZIP下载]
If you want to download a finished project, the link is at the end of this article.
如果要下载完成的项目,则该链接位于本文的末尾。
概念分解 (Concept Breakdown)
For saving the in-game data to a hard drive in a format that can be understood and loaded later on, we will be using a .NET/Mono feature known as Serialization. You can find out more about theory of serialization at the following links:
为了将游戏中的数据以一种可以理解并稍后加载的格式保存到硬盘驱动器,我们将使用一种称为序列化的.NET / Mono功能。 您可以在以下链接中找到有关序列化理论的更多信息:
In short, “serializing” means writing down a .NET object to a hard drive in its raw binary form. It may sound a bit unintuitive, but think of it this way: we’re saving an instance of a class to a hard drive.
简而言之,“序列化”是指将.NET对象以其原始二进制格式写到硬盘中。 听起来可能有点不直观,但是请这样想:我们将类的实例保存到硬盘中。
You may remember that while finishing up our last example, we wrapped our player’s data into a single class. You may already be able to tell where this is going. Let’s just go over the logic flow real quick:
您可能还记得,在完成最后一个示例时,我们将播放器的数据包装到一个类中。 您可能已经能够知道前进的方向。 让我们快速回顾一下逻辑流程:
Saving data:
保存数据:
- Get a class containing player’s data 获取一个包含玩家数据的类
- Serialize down to hard drive into known file 向下序列化到硬盘驱动器到已知文件
Loading data:
加载数据中:
- Find known save file 查找已知的保存文件
Deserialize the contents into generic object
将内容反序列化为通用对象
Cast object into the type of our data class
将对象转换为数据类的类型
What do we need to save?
我们需要保存什么?
- Everything that was already in the PlayerStatistics class which was saved across scenes PlayerStatistics类中已经存在的所有内容,已跨场景保存
- Scene ID where the game was saved 保存游戏的场景ID
- Location in the scene where the player was when the game was saved 保存游戏时玩家所在的场景中的位置
准备事情 (Preparing Things)
Using the project from our previous example, we will need to prepare some things in order to begin writing this functionality correctly. We need to consider the following problems:
使用上一个示例中的项目,我们将需要准备一些东西,以便开始正确地编写此功能。 我们需要考虑以下问题:
- What scene was the player on when the game was saved? 保存游戏时,玩家处于哪个场景?
- Where in the scene was the player? 玩家在场景中的什么地方&#x