我想重构我的加载游戏脚本

I want to refactor my loading game script

我想在 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;
        }
    }
}

Return 代码到 start() 像以前一样,而不是 update() 使用在编辑 >> 项目设置 >> 脚本执行顺序中执行代码:

您可以使用 Awake() 函数:https://docs.unity3d.com/ScriptReference/MonoBehaviour.Awake.html

此方法总是在开始之前调用。

要使用它,您可以将 SaveLoad 中的 Start 函数重命名为 Awake。 然后,您可以在 FirstToLoad class

中使用 Start 中 Update 中的函数