Unity 多场景数据持久化:防止数据覆盖
要实现在Unity中多个场景之间共享数据并且不覆盖现有数据,你可以考虑使用持久化数据的方法。下面是修改后的代码示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Xml.Serialization;
using System.IO;
public class SavePassAcc : MonoBehaviour
{
public static SavePassAcc Instance;
public PlayerS playerStats;
public GameObject UIStuff;
void Awake()
{
if (Instance == null)
{
DontDestroyOnLoad(this.gameObject);
Instance = this;
}
else if (Instance != this)
{
Destroy(gameObject);
}
LoadData();
}
void Start()
{
}
public void SaveData()
{
// 创建一个新的XML文件
XmlSerializer serializer = new XmlSerializer(typeof(PlayerS));
// 创建一个文件覆盖其中存在的任何内容 - 首先检查路径
FileStream stream = new FileStream(Application.persistentDataPath + "/pla.xml", FileMode.Create);
// 将数据序列化为XML并保存到文件中
serializer.Serialize(stream, playerStats);
stream.Close();
}
public void LoadData()
{
// 检查文件是否存在,如果不存在则返回
string filePath = Application.persistentDataPath + "/pla.xml";
if (!File.Exists(filePath))
{
return;
}
// 打开XML文件并反序列化数据
XmlSerializer serializer = new XmlSerializer(typeof(PlayerS));
FileStream stream = new FileStream(filePath, FileMode.Open);
playerStats = (PlayerS)serializer.Deserialize(stream);
stream.Close();
// 更新UI中的数据
if (UIStuff != null)
{
UIStuff.GetComponent<CavanPass>().NameField.text = playerStats.NameField;
UIStuff.GetComponent<CavanPass>().PwdField.text = playerStats.PwdField;
}
}
}
[System.Serializable]
public class PlayerS
{
public string NameField;
public string PwdField;
}
在这个示例中,我将保存的XML文件路径更改为Application.persistentDataPath,这样可以在运行时持久化保存数据。这样,即使在不同的场景之间加载,数据也不会被覆盖。在LoadData()方法中,我添加了一个检查,以确保文件存在,避免在第一次运行时出错。
原文地址: http://www.cveoy.top/t/topic/bSjp 著作权归作者所有。请勿转载和采集!