我想在 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;
}
}
}
uj5u.com熱心網友回復:
將代碼恢復為start()以前的樣子,而是update()使用在編輯>>專案設定>>腳本執行順序中執行代碼:

uj5u.com熱心網友回復:
您可以使用 Awake() 函式:https ://docs.unity3d.com/ScriptReference/MonoBehaviour.Awake.html
此方法總是在 Start 之前呼叫。
要使用它,您可以將 SaveLoad 中的 Start 函式重命名為 Awake。然后,您可以在 FirstToLoad 類的 Start 中使用 Update 中的函式
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/471728.html
上一篇:Vagrant詳細教程
