So far…
My save code takes basic game object data from the scene and adds it to a list to be serialized.
My load code takes the serialized list and Instantiates a prefabs from the basic data.
I now have a requirement to use the scene tree structure within unity and need to Instantiate the prefabs in the correct tree. I would like some advice on how to store the Parent/Child relationship in the save data.
I was thinking of adding a unique number to each saved game object (At save time) and having the child object reference that number. Then at load time re-establish the tree from this data.
This is going to add some complexity to the SaveLoad class, is there an easier/better way?
Current working code.
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MTC_SaveLoad : MonoBehaviour {
public Transform topLevelGameObject;
private MTC_PersistentDataSaverLoader dataSaverLoader;
public InputField _userNameInputField;
void Start () {
dataSaverLoader = new MTC_PersistentDataSaverLoader();
}
public void Save()
{
Debug.Log("Save");
SaveDataObjectList listOfObjectsToSave = new SaveDataObjectList();
listOfObjectsToSave.blocks = new List<GameObjectSaveData>();
GameObjectSaveData block;
Transform[] objChildren = topLevelGameObject.GetComponentsInChildren<Transform>();
foreach (Transform obj in objChildren)
{
if (obj.tag == "MountPoint")
{
Debug.Log(obj.name);
block = new GameObjectSaveData();
block.resourceName = obj.name;
block.positionX = obj.transform.localPosition.x;
block.positionY = obj.transform.localPosition.y;
block.positionZ = obj.transform.localPosition.z;
listOfObjectsToSave.blocks.Add(block);
}
}
dataSaverLoader.SaveBF(_userNameInputField.text + ".dat", listOfObjectsToSave);
}
public void Load()
{
Debug.Log("Load");
SaveDataObjectList loadBlocks = (SaveDataObjectList)dataSaverLoader.LoadBF(_userNameInputField.text + ".dat");
GameObject loadedGameObject;
BlockControllerV3 bc;
foreach (GameObjectSaveData block in loadBlocks.blocks)
{
if (block.resourceName == "BlockBasic" || block.resourceName == "BlockHover" || block.resourceName == "BlockSideForce" || block.resourceName == "BlockForwardForce")
{
loadedGameObject = (GameObject)Instantiate(Resources.Load(block.resourceName));
bc = loadedGameObject.GetComponent<BlockControllerV3>();
bc.onAddBlockToMechController(topLevelGameObject);
loadedGameObject.transform.localPosition = new Vector3(block.positionX, block.positionY, block.positionZ);
loadedGameObject.transform.rotation = topLevelGameObject.transform.rotation;
loadedGameObject.name = block.resourceName;
}
}
}
}
[Serializable]
public class GameObjectSaveData
{
public float positionX;
public float positionY;
public float positionZ;
public string resourceName;
}
[Serializable]
public class SaveDataObjectList
{
public List <GameObjectSaveData> blocks;
}
Yup, saving parent/child relationships by ID is the way to go. It requires you to do loading in two passes instead of one, but otherwise shouldn’t be complex.
After contemplating why you needed the two passes on the load, it inspired me to implement a recursive function to recreate the game objects from the list data. Not implemented it fully but have Debug.Log the output and it looks like it will work as expected. I must admit I’m surprised at how simple the end solution is (Not finished yet, need to pass the newly created parent to the child).
public void Load()
{
SaveDataObjectList loadBlocks = (SaveDataObjectList)dataSaverLoader.LoadBF(_userNameInputField.text + ".dat");
CreateRecursiveFromID(loadBlocks.topLevelInstanceID, loadBlocks);
}
public void CreateRecursiveFromID(int id, SaveDataObjectList loadBlocks)
{
CreateObjectFromID(id, loadBlocks); // Create the object first before creating children.
foreach (GameObjectSaveData block in loadBlocks.BlocksWithParentID(id))
{
CreateRecursiveFromID(block.instanceID, loadBlocks);
}
}
I will try and make the code a little more generic and post the working solution in a few days.
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MTC_SaveLoad : MonoBehaviour {
public Transform topLevelGameObjectTranform;
private MTC_PersistentDataSaverLoader dataSaverLoader;
public InputField _userNameInputField;
void Start () {
dataSaverLoader = new MTC_PersistentDataSaverLoader();
}
public void Save()
{
Debug.Log("Save");
SaveDataObjectList listOfObjectsToSave = new SaveDataObjectList();
listOfObjectsToSave.blocks = new List<GameObjectSaveData>();
GameObjectSaveData block;
Transform[] objChildren = topLevelGameObjectTranform.GetComponentsInChildren<Transform>();
listOfObjectsToSave.topLevelInstanceID = topLevelGameObjectTranform.GetInstanceID();
foreach (Transform obj in objChildren)
{
block = new GameObjectSaveData();
block.resourceName = obj.name;
block.positionX = obj.transform.position.x;
block.positionY = obj.transform.position.y;
block.positionZ = obj.transform.position.z;
block.RotX = obj.transform.rotation.x;
block.RotY = obj.transform.rotation.y;
block.RotZ = obj.transform.rotation.z;
block.scaleX = obj.transform.localScale.x;
block.scaleY = obj.transform.localScale.y;
block.scaleZ = obj.transform.localScale.z;
block.instanceID = obj.transform.GetInstanceID();
block.parentInstanceID = obj.transform.parent.GetInstanceID();
Debug.Log("Save Name=" + obj.name + " instanceID=" + block.instanceID + " parentInstanceID=" + block.parentInstanceID);
listOfObjectsToSave.blocks.Add(block);
}
dataSaverLoader.SaveBF(_userNameInputField.text + ".dat", listOfObjectsToSave);
}
public void Load()
{
SaveDataObjectList blocks = (SaveDataObjectList)dataSaverLoader.LoadBF(_userNameInputField.text + ".dat"); //
CreateRecursiveFromID(blocks.topLevelInstanceID, blocks, topLevelGameObjectTranform.parent.transform); // neeed to do the parent as GetComponentsInChildren also saves the game object at that level.
}
public void CreateRecursiveFromID(int id, SaveDataObjectList blocks, Transform parentGameObject)
{
Transform childGameObjectTransform = CreateGameObjectFromGameObjectSaveData(blocks.BlockWithinstanceID(id), parentGameObject); // Create the object first before creating children.
//childGameObjectTransform.parent = parentGameObject;
foreach (GameObjectSaveData block in blocks.BlocksWithParentID(id))
{
CreateRecursiveFromID(block.instanceID, blocks, childGameObjectTransform); // The child now becomes the parent
}
}
public Transform CreateGameObjectFromGameObjectSaveData(GameObjectSaveData block, Transform parentGameObject)
{
Debug.Log("Load Name=" + block.resourceName + " instanceID=" + block.instanceID + " parentInstanceID=" + block.parentInstanceID);
Debug.Log(" positionX" + block.positionX + " positionY" + block.positionY + "positionZ" + block.positionZ);
GameObject newGameObject;
if (block.resourceName == "BlockBasic" || block.resourceName == "BlockHover" || block.resourceName == "BlockSideForce" || block.resourceName == "BlockForwardForce" || block.resourceName == "MechController")
{
newGameObject = (GameObject)Instantiate(Resources.Load(block.resourceName));
}
else
{
newGameObject = new GameObject(); // If we dont have a prefab then create an empty game object. This is a shortcut to ensure we always have a parent but will lead to problems with unused empty gameobjects. This will need to be removed or some sort of cleanup needs to be done.
}
newGameObject.transform.parent = parentGameObject;
newGameObject.transform.position = new Vector3(block.positionX, block.positionY, block.positionZ);
newGameObject.transform.rotation = Quaternion.Euler(block.RotX, block.RotY, block.RotZ);
newGameObject.transform.localScale= new Vector3(block.scaleX, block.scaleY, block.scaleZ);
newGameObject.name = block.resourceName;
return newGameObject.transform;
}
}
[Serializable]
public class GameObjectSaveData
{
public float positionX;
public float positionY;
public float positionZ;
public float RotX;
public float RotY;
public float RotZ;
public float scaleX;
public float scaleY;
public float scaleZ;
public string resourceName;
public int parentInstanceID;
public int instanceID;
}
[Serializable]
public class SaveDataObjectList
{
public int topLevelInstanceID;
public List <GameObjectSaveData> blocks;
public GameObjectSaveData BlockWithinstanceID(int id)
{
GameObjectSaveData block=blocks.Find(c => c.instanceID == id);
return block;
}
public List<GameObjectSaveData> BlocksWithParentID(int id)
{
List<GameObjectSaveData> newList = blocks.FindAll(c => c.parentInstanceID == id);
return newList;
}
}