当前位置:网站首页>Unity foundation 3- data persistence
Unity foundation 3- data persistence
2022-07-28 20:55:00 【W.C.Zeng】
ScriptableObject
Save common data types , Can be in inspector View in window , for example
Put the monster 、 The player's attributes are saved as ScriptableObject
《 Wheat field story 》 In the series , Save the item data as ScriptableObject Similar to the following
using UnityEngine;
using System.Collections.Generic;
[CreateAssetMenu(fileName = "CropData", menuName = "CropData/CropData", order = 0)]
public class CropDataList_SO : ScriptableObject
{
/// <summary>
/// Crop database
/// </summary>
public List<CropDetails> cropDetailsList;
}
And then you can do it in project Window , Right click to create ItemData
Fill in the data and use public ItemData itemDataList;
PlayerPrefs
Here is 3DRPG In the basic series 《SaveManager.cs》 An example of saving player data
Save the key-value pair , But it can cooperate JsonUtility To save objects
private void Save(Object data, string key)
{
var jsonData = JsonUtility.ToJson(data);
PlayerPrefs.SetString(key, jsonData);
PlayerPrefs.SetString(sceneName, SceneManager.GetActiveScene().name);
PlayerPrefs.Save();
}
private void Load(Object data, string key)
{
if (PlayerPrefs.HasKey(key))
{
JsonUtility.FromJsonOverwrite(PlayerPrefs.GetString(key), data);
}
}
Another layer of encapsulation is used
public void LoadPlayerData()
{
var data = GameManager.Instance.playerStats.characterData;
Load(data, data.name);
}
public void SavePlayerData()
{
var data = GameManager.Instance.playerStats.characterData;
Save(data, data.name);
}
Different operating systems have different save paths
File systems store data
Use official JSON package Newtonsoft Json
The following example is 《 Wheat field story 》 in , Use 3 An archive bar saves data
Use the interface for different objects that need archiving function (GUID) Expand the archiving function
public interface ISaveable
{
string GUID {
get; }
GameSaveData GenerateSaveData();
void RestoreSaveData(GameSaveData saveData);
// since C Sharp 9.0 After version , You can implement methods in an interface
// Write a registration method in this interface
void RegisterSaveable()
{
SaveLoadManager.Instance.RegisterSaveable(this);
}
}
obtain GUID
using UnityEngine;
[ExecuteAlways]
public class DataGUID : MonoBehaviour
{
// Mount on the object that needs to be stored , Realize the uniqueness of stored data
public string guid;
private void Awake() {
if (guid==string.Empty)
{
// 16 Bit length string
guid = System.Guid.NewGuid().ToString();
}
}
}
Read and write data
private void Save(int index)
{
// Where to save it
DataSlot data = new DataSlot();
foreach (var saveable in saveableList)
{
data.dataSlotDict.Add(saveable.GUID, saveable.GenerateSaveData());
}
dataSlotList[index] = data;
// After serialization, write to the file to store
// The final path
var resultPath = jsonFolder + "data" + index + ".sav";
// Store in indented format Serialized data
var jsonData = JsonConvert.SerializeObject(dataSlotList[index], Formatting.Indented);
if (!File.Exists(resultPath))
{
Directory.CreateDirectory(jsonFolder);
}
// write file
File.WriteAllText(resultPath, jsonData);
}
Reading data
public void Load(int index)
{
currentDataIndex = index;
var resultPath = jsonFolder + "data" + index + ".sav";
if (File.Exists(resultPath))
{
var stringData = File.ReadAllText(resultPath);
// Deserialization
var jsonData = JsonConvert.DeserializeObject<DataSlot>(stringData);
foreach (var saveable in saveableList)
{
saveable.RestoreSaveData(jsonData.dataSlotDict[saveable.GUID]);
}
}
else
{
Debug.LogError(" The archive file is missing ");
}
}
When using interfaces , Register first , Then implement the corresponding method public class TransitionManager : Singleton<TransitionManager>, ISaveable
void Start()
{
ISaveable saveable = this;
saveable.RegisterSaveable();
fadeCanvasGroup = FindObjectOfType<CanvasGroup>();
}
public GameSaveData GenerateSaveData()
{
GameSaveData saveData = new GameSaveData();
saveData.dataSceneName = sceneName;
return saveData;
}
public void RestoreSaveData(GameSaveData saveData)
{
// Debug.Log(" Reload scene ");
sceneName = saveData.dataSceneName;
// Archive by game , Reload the scene content
StartCoroutine(LoadSaveDataScene(sceneName));
}
边栏推荐
- 使用ORDER BY 排序
- Explain several mobile ways of unity in detail
- Use order by to sort
- H5 wechat shooting game source code
- Space shooting Lesson 13: explosion effect
- [C language brush questions] explanation of linked list application
- Yyds dry inventory interview must brush top101: every k nodes in the linked list are turned over
- Learn about the native application management platform of rainbow cloud
- js飞入js特效弹窗登录框
- Understanding of C # delegate
猜你喜欢

Thinking and summary of R & D Efficiency

H5 wechat shooting game source code

Redis入门二:redhat 6.5安装使用

Explain the life cycle function in unity in detail

Interesting pictures and words

Why on earth is it not recommended to use select *?

Explain various coordinate systems in unity in detail

Talking about canvas and three rendering modes in unity

融合数据库生态:利用 EventBridge 构建 CDC 应用

Prometheus complete process of configuring alertmanager
随机推荐
Space shooting Lesson 11: sound and music
Two written interview questions about regular
Thinking and summary of R & D Efficiency
华为云数字资产链,“链”接数字经济无限精彩
企业如何成功完成云迁移?
Explain rigid body and collider components in unity
User and group and authority management
Redis入门二:redhat 6.5安装使用
Classes and objects (medium)
Want to draw a picture that belongs to you? AI painting, you can also
JS picture hanging style photo wall JS special effect
Pl515 SOT23-5 single / Dual Port USB charging protocol port controller Parkson electronic agent
What is data center? What value does the data center bring_ Light spot technology
Space shooting lesson 09: elf animation
【服务器数据恢复】HP StorageWorks系列存储RAID5两块盘故障离线的数据恢复案例
How do we do full link grayscale on the database?
一个程序员的水平能差到什么程度?尼玛,都是人才呀...
如何平衡SQL中的安全与性能?
PostgreSQL数据库删库前是不是需要把所有连接断开才能删除?
Integrating database Ecology: using eventbridge to build CDC applications