Hello.
I’ve done a hefty amount of googling and searching on Answers for this one. My problem is that I want to save a scene as it is (think of Total War’s strategy map), go fight a battle (like Total War battle using the armies from the strategy map), then come back to the strategy map as it was, except with some units now dead or injured.
I’ve done tutorials on serialization and can save things like a simple health value, but to be practical I really need to save the scene as it is, or save a ‘bucket’ with every GameObject that’s in the hierarchy in it.
Here’s my script for the latter attempt:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections.Generic;
public class SaveAndLoad : MonoBehaviour {
public static SaveAndLoad saveandload;
public bool usingSaveA = true;
private int SAVEaORb;
private int LOADaORb;
public List<GameObject> saveBucket;
void Awake()
{
if(saveandload == null)
{
DontDestroyOnLoad(gameObject);
saveandload = this;
}
else if (saveandload != this)
{
Destroy(gameObject);
}
}
public void SaveTemporary()
{
if(usingSaveA)
{
SAVEaORb = 1;
usingSaveA = false;
LOADaORb = 1;
}
else
{
SAVEaORb = 2;
usingSaveA = true;
LOADaORb = 2;
}
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Create (Application.persistentDataPath + "/tempSave" + SAVEaORb + ".dat");
STRGameData data = new STRGameData ();
//PUT DATA BELOW HERE IN THE FORM data.xy&z = xy&z
foreach (GameObject obj in Resources.FindObjectsOfTypeAll<GameObject>())
{
saveBucket.Add (obj);
}
data.saveBucket = saveBucket;
bf.Serialize (file, data);
file.Close ();
}
public void LoadTemporary()
{
if(File.Exists(Application.persistentDataPath + "/tempSave" +SAVEaORb +".dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/tempSave" +LOADaORb + ".dat", FileMode.Open);
STRGameData data = (STRGameData)bf.Deserialize(file);
file.Close();
//PUT DATA BELOW HERE IN THE FORM xy&z = data.xy&z
saveBucket = data.saveBucket;
}
}
}//end of MONOBEHAVIOUR
[Serializable]
class STRGameData
{
public List<GameObject> saveBucket;
}
NOTE: the ‘saveAorB’ is set up just to allow me to have two fallback autosaves, instead of one. Like HalfLife did.
Apparently GameObjects aren’t serializable though, according to my research and since I’m getting this error:
Without resorting to plugins (which I am aware of but want to try do this the “correct” way) what options have I? Can I make GameObjects serializable? Can I save an entire scene the way it is at a moment in time?
Thanks
Kevin