- Home /
How to save and load mobs?
So I've been looking at creating a saving and loading system for my game.
The tutorials I've been looking at have basically been suggesting to create a serializable class with all the values I want to save and then to turn it into a json, xml or binary file.
Now I'm facing the problem that I don't just want to save my player stats and position, but I also want to save the positions and stats of mobile objects such as enemies or other NPCs. Some of these even spawn later in the game, so it's not like they're necessarily available when the scene starts.
Is there some easy way to save mobs like that? I tried to just save the GameObjects, but that only saves the reference (which is useless on load) to the GameObject in the inspector, but doesn't serialize all the sub components such as the Transform or other Monobehaviors, which I want.
public class SavingManager : MonoBehaviour
{
public Transform saveParent;
private string jsonSave;
public void Save()
{
List<GameObject> objects = new List<GameObject>();
foreach (Transform trans in saveParent)
{
if(trans != saveParent) objects.Add(trans.gameObject);
}
TestSave save = new TestSave(objects);
string json = JsonUtility.ToJson(save);
Debug.Log(json);
jsonSave = json;
foreach (Transform trans in saveParent)
{
GameObject game = null;
if(trans != saveParent) game = trans.gameObject;
if(game != null) Destroy(game);
}
}
public void Load()
{
TestSave save = JsonUtility.FromJson<TestSave>(jsonSave);
foreach (GameObject obj in save.Objects)
{
Instantiate(obj,saveParent);
}
}
}
What's the best way to do this?