我想在 Start() 中加载我的保存文件,但出现错误,没有加载文件的路径,因为路径是在 Start() 中创建的,所以我将加载位置更改为 Update(),我想问的是有比我使用的更好、更优化的选择吗?
using UnityEngine;
public class FirstToLoad : MonoBehaviour
{
public SaveLoad saveLoad;
public LoadScene loadScene;
public bool isGameLoaded;
// Start is called before the first frame update
void Start()
{
StartCoroutine(loadScene.Load_End());
}
void Update()
{
if(!isGameLoaded){
saveLoad.Load();
isGameLoaded = true;
}
}
}
如果有人需要知道我的 SaveLoad 脚本的外观
using UnityEngine;
using System.IO;
public class SaveLoad : MonoBehaviour
{
private string jsonSavePath;
DataToSave gameData;
DataManager moreGameData;
void Start(){
jsonSavePath = Application.persistentDataPath + "/PlayerStats.json";
moreGameData = GetComponent<DataManager> ();
gameData = GetComponent<DataToSave> ();
}
public void Save(){
//Creating file or opening file
FileStream File1 = new FileStream(jsonSavePath, FileMode.OpenOrCreate);
//Data to save
moreGameData.SaveGame();
//!Saving data
string jsonData = JsonUtility.ToJson(gameData, true);
File1.Close();
File.WriteAllText(jsonSavePath, jsonData);
}
public void Load(){
string json = ReadFromFile("PlayerStats.json");
JsonUtility.FromJsonOverwrite(json, gameData);
moreGameData.LoadGame();
}
private string ReadFromFile(string FileName){
using(StreamReader Reader = new StreamReader(jsonSavePath)){
string json = Reader.ReadToEnd();
return json;
}
}
}
最佳答案
关于c# - 我想重构我的加载游戏脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72137819/