Writing variables in external files

Hello all,

I got 2 scenes between which I want to transfer a variable. I found a couple of ways to do that, my question is how to do it by writing a file from one file and reading it with the other?

I got something like this so far:

string lgCode = "Somestring value";
byte[] bytes = Encoding.ASCII.GetBytes(lgCode);
System.IO.File.WriteAllBytes("../lg.xml", bytes);

Now I got 2 questions, how to read from that file from a script in the othe scene?
and how to know where is the location the script is in?

Can you give me some best practices for finding the path? reading from file and migrating the byte to string?

OR

Just a better way to save the var when the app is shutdown

OR just a better way to migrate vars between scenes.

Thank you!

Better way to migrate vars between scenes: a static variable pointing to a class holding your data:

[System.Serializable]
public class SomeData {
public string foo;
}

// elsewhere
public class SomeGameManager : MonoBehaviour {
public static SomeData thisGameData;

void Awake() {
thisGameData = new SomeData() { foo = "Somestring value" };
}
}

// elsewhere
public class SomeOtherSceneScript : MonoBehaviour {
void Start() {
Debug.Log($"The value is {SomeGameManager.thisGameData != null ? SomeGameManager.thisGameData.foo : "NULL"}");
}
}

Better way to save data to disk: JsonUtility

//this is why I put the data above in a class with System.Serializable
public class SaverLoader : MonoBehaviour {
public void SaveData() {
string json = JsonUtility.ToJson(SomeGameManager.thisGameData);
System.IO.File.WriteAllText( Path.Combine(Application.persistentDataPath, "someFile.json"), json);
}

public void LoadData() {
string json = System.IO.File.ReadAllText(Path.Combine(Application.persistentDataPath, "someFile.json"));
SomeGameManager.thisGameData = JsonUtility.FromJson<SomeData>(json);
}
}

Well just the opposite of what you’ve done so far…
https://docs.microsoft.com/en-us/dotnet/api/system.io.file.readallbytes?view=netcore-3.1

Have some constant name for the file, and put it in in this folder: path: https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html That’s important because the location of a reliably writeable folder will be different per operating system, and that property will give you such a folder.

If you just need data to persist between scenes and not between when the game is shut down and started back up, you can use https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html to keep an object around between scenes, or use static variables.

Thank you both of you! So much to dig in :)!