Hello everybody. I’m having some File Sharing problems in unity. I need to save and load objects from a few Json files and even though I used StreamReader.Close(), it doesn’t seem to work as it should. I’m a bit slow with those backend code stuff, so I really don’t know what I’m doing wrong. Does anyone have any suggestion?
using UnityEngine;
using System.Collections;
using System.IO;
using System.Text;
public class SaveLoadManager : MonoBehaviour {
public SaveData saveData;
public static SaveLoadManager manager;
void Awake(){
if (manager == null) {
manager = this;
} else if (manager != null) {
Destroy (gameObject);
}
DontDestroyOnLoad (gameObject);
}
public static string LoadJsonAsResource(string path){
string jsonFilePath = path.Replace (".json", "");
TextAsset loadedJsonfile = Resources.Load<TextAsset> (jsonFilePath);
return loadedJsonfile.text;
}
public string LoadJsonAsExternalResource(string path){
path = Application.persistentDataPath + "/" + path;
if (!File.Exists (path)) {
return null;
}
StreamReader reader = new StreamReader (path);
string response = "";
while (!reader.EndOfStream) {
response += reader.ReadLine();
}
return response;
reader.Close ();
}
public void WriteJsonToExternalResource(string path, string content){
path = Application.persistentDataPath + "/" + path; //caminho do arquivo
FileStream stream = File.Create (path);//cria o arquivo
byte[] contentBytes = new UTF8Encoding (true).GetBytes (content);//converting the string into bytes
stream.Write(contentBytes,0,contentBytes.Length);//escreve os dados no arquivo
stream.Close ();
}
}