c# - 我想重构我的加载游戏脚本

标签 c# performance unity-game-engine refactoring

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

最佳答案

像以前一样将代码返回到start(),并使用update()在编辑>>项目设置>>脚本执行顺序中执行代码:

Script Execution Order

关于c# - 我想重构我的加载游戏脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72137819/

相关文章:

c# - 如何计算 C# 中的日期是否晚于 6 个月的生日

非集群环境下分区表的mysql select查询优化

android - 有什么方法可以加快 Android 模拟器的速度

performance - 为什么纹理查找比直接计算慢得多?

git - Unity - Git LFS - 新存储库上的 "This repository is over its data quota"

ios - Unity ios 错误生成 GameSparksWebSocket.h 文件未找到 GSExternal.m

c# - 如何以编程方式使用 SVN 和 .NET 进行文件版本控制?

c# - 将 PropertyInfo.PropertyType 转换为枚举

c# - 即使对于新的上下文,OnModelCreating 也只调用一次

ios - Unity iOS IPv6 - IL2CPP UnityEngine.Experimental.Networking 崩溃