Nech Nech - 14 days ago 5
C# Question

How do I save custom variables in Unity3D?

I'm working on a save and load system for my game in Unity3D. The basics like position is simple, I just have

public void Save() {

PlayerPrefs.SetFloat ("X", transform.position.x);
PlayerPrefs.SetFloat ("Y", transform.position.y);
PlayerPrefs.SetFloat ("Z", transform.position.z);

}

public void Load() {

float x = PlayerPrefs.GetFloat ("X");
float y = PlayerPrefs.GetFloat ("Y");
float z = PlayerPrefs.GetFloat ("Z");

transform.position = new Vector3 (x, y, z);

}


But then comes the part when I want to save custom variables.
Here's how the class that contains them looks like:

[SerializeField] private Stat health;
public static Stat Health { get; set; }
[SerializeField] private Stat exp;
public static Stat Exp { get; set; }
[SerializeField] private Stat oxygen;
public static Stat Oxygen { get; set; }
[SerializeField] private Stat playerLevel;
public static Stat PlayerLevel { get; set; }


So my question is, how do I get values of those stats in my SaveLoad script?

Answer

Just to drive home the point

1) In Unity

Totally forget about Serialization. It's that simple.

I can't even be bothered discussing why. It's just how it is.

2) Generally these days in games/mobile you should

Work with JSON

End of story. Fortunately it is incredibly easy.

3) To convert back and fore to JSON,

Do exactly what @Programmer says.

http://stackoverflow.com/a/40097623/294884

4) Finally to save that, honestly there's nothing wrong with:

Simply use PlayerPrefs to save the long JSON string. No worries.

Note that if you DO want to just save it as a text file, which is fine, this is dead easy.

Just do this: http://stackoverflow.com/a/35941579/294884

(Never use "streamwriter" in Unity for any reason. It's totally trivial to save/read text files; shown there.)

Repeat. Do >> NOT << touch, think about, or use "serialization" in Unity! For any reason, ever!

Enjoy life!

Comments