如何使用 unity3d odin插件来保存数据和读取数据呢?
下面是直接的代码,使用后使用按键来操作保存和读取
using System.IO;
using Sirenix.Serialization;
using UnityEngine;
public class DataHandler : MonoBehaviour
{
private string savePath;
public UserInfo userInfo = new UserInfo();
private void Start()
{
// 设置保存路径
savePath = Application.persistentDataPath + "/saveData.dat";
userInfo.userAge = 30;
userInfo.userName = "JohnDoe";
// 创建一个示例数据对象
// 保存数据
// 读取数据
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.Q))
{
SaveData(userInfo);
Debug.Log("保存数据");
}
if (Input.GetKeyDown (KeyCode.W))
{
userInfo.userAge++;
Debug.Log("设置了数据");
}
if (Input.GetKeyDown (KeyCode.E))
{
UserInfo loadedUserInfo = LoadData();
Debug.Log("Loaded User Name: " + loadedUserInfo.userName);
Debug.Log("Loaded User Age: " + loadedUserInfo.userAge);
Debug.Log("读取了数据");
}
}
private void SaveData(UserInfo data)
{
byte[] bytes = SerializationUtility.SerializeValue(data, DataFormat.Binary);
File.WriteAllBytes(savePath, bytes);
}
private UserInfo LoadData()
{
if (File.Exists(savePath))
{
byte[] bytes = File.ReadAllBytes(savePath);
return SerializationUtility.DeserializeValue<UserInfo>(bytes, DataFormat.Binary);
}
else
{
Debug.LogWarning("Save data not found");
return null;
}
}
}
[System.Serializable]
public class UserInfo
{
public string userName;
public int userAge;
}