UNITY C# - How can I save a Game Object, that has been instantiated in a runtime, in a runtime?

Viewed 1773

Ive got a Game Object that I instantiate in a runtime. Then, I make some changes to it like: I add some children objects, components etc. I would like to somehow save this newly created object for me to use in other scenes and sessions. Question is: how? Thank you.

PS obviously I cannot use UnityEditor namespace

1 Answers

If you want to re-use the object in other scenes, you can use DontDestroyOnLoad method to prevent it from getting destroyed upon changing scenes. Afterwards, if you goal is to spawn copies of this object, you can disable it and treat it as a prefab and instantiate copies of it when necessary.

If you want to be able to re-use an object after re-launching the game, you might wanna check out ways of saving data in Unity. One simple way would be using PlayerPrefs but you would have to write the code for loading/saving the state of your object on your own since it's capable of directly saving only int, float, string data type values.

Here are a couple of references: https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

EDIT:

A more specific solution you can try is serializing a custom class made by you to a JSON file. That class would contain the necessary data to re-create whatever GameObject you had in the scene.

Creating a prefab outside the editor isn't an option. Here's a reference: https://www.reddit.com/r/Unity3D/comments/a5c02u/save_gameobject_as_prefab_at_runtime/

Related