Saving a game object instantiated after runtime.

Greetings!
I’m rather new to Unity/C#, and I have a bit of a problem when saving data.
I have a game object that, when the player interacts with it, becomes a new and different game object.

I’ve been looking for a way to save that change. To make matters worse, I’m spawning the new object from a Prefab (Because it’s sort of a building game), so I would need to generate an ID for the new object upon instantiation.

I’ve already watched the tutorial on persistence, and while that works fantastically to save data of gameobjects present at runtime, it’s working for this.

Edit For clarification: Is there a way to save game objects created after runtime, so they can be loaded later?

Thanks!

Because you can save only simple types like floats, strings, ints, bools, and arrays and lists of those you need a system that will go from game objects and its components to data and back again. Let’s say you need to store position only. You should start with creating a class that stores some kind of saveable prefab ID and whatever you want to save, position in this case.

[System.Serializable]

public class GameObjectSaveData

{

public int id;

public float x;

public float y;

public float z;

// put constructor here

}

It is System.Serializable so you can actually save it. Now let’s create some simple container for those;

[System.Serializable]

public class GameData

{

public List < GameObjectSaveData "> objects;

// put constructor here

}

Now something for saving it. Two scripts, one calls an event to every saveable game object and second who actually makes a game object saveable.

public static class GameSaveLoad

{

public delegate void SaveData(GameData Data);

public static event SaveData SaveDataEvent;

public void Save()
{

GameData data = new GameData();

if (SaveDataEvent != null)

SaveDataEvent(data);
BinaryFormatter bf = new BinaryFormatter();

Now u should know the rest of it after watching the tutorial. And the game object script

public class SavingComponent : MonoBehaviour
{

public int id;

private void OnEnable()

{

GameSaveLoad.SaveDataEvent += Save;

}

private void OnDisable()

{

GameSaveLoad.SaveDataEvent -= Save;

}

public void Save(GameData data)

{

data.objects.Add(new ObjectData(id, transform.position.x, //etc etc ))

}

So now you have them saved. Loading is the rest. You said you know how to instantiate them - you only need some kind of Spawner with Spawn function, that will choose specific prefab from a list basing on its ID and put it in right place.

You really should make this kind of list with ScriptaleObject. If you are unfamiliar with events I can explain them. I haven’t type the code into Unity so it might not work, but it surely shows the idea and my own Save System is like this.

My English is not perfect so sorry if I made anything unclear.

Yea

@Pogoda answer is good. Do that.