how can i save the gameobject to file and load it?

I created a gameobject at run time and i want to save this gameobject to file and after reload the scene. I want to load this gameobject with all component. Is it possible?

Yes it is.

  1. Make sure the to make a prefab out of the object

  2. Save object code:

    public static class DataManager
    {
        public static GameObject SavedGameObject;
        string path = "Path/To/Save/Location";
    
        public static bool Save(GameObject obj)
        {
                string data;
                //Translate GameObject into path
                string assetPath = AssetDatabase.GetAssetPath((GameObject)data);
                if (assetPath == null) return false;
                else data= assetPath;
    
            //Encrypt Save Data (not nessecary, but nice to have)
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(path, FileMode.Create);
    
            formatter.Serialize(stream, data);
    
            stream.Close();
    
            return true;
        }
    
         
        public static object Load()
        {
            if (File.Exists(path))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                FileStream stream = new FileStream(path, FileMode.Open);
    
    
                data = formatter.Deserialize(stream) as string
                SavedGameObject = (GameObject)AssetDatabase.LoadAssetAtPath((string)data[key].Key, typeof(GameObject));
               
                stream.Close();
            }
            else
            {
                Debug.LogWarning("Save file not found.");
                return null;
            }
        }
    }
    
  3. The code stored the game object path as string and then loads the gameobject from the path again. The code is more for explanation and my not work right of. It is not tested, just edited some pieces of my own code and send it over to you.

Pls watch this video :slight_smile: Tutorial video