I wanted to load my save files in Start() but I got an error that there is no path to load file because the path is created in Start() so I changed loading place to Update() and I wanna ask is there a better and more optimal option than what I used?
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;
}
}
}
If someone needs to know how my SaveLoad script looks
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;
}
}
}
CodePudding user response:
Return the code to start()
like before and instead update()
use executing the code in Edit >> Project Setting >> Script Execution Order: