- Home /
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?
Answer by Phodex_Games · Jul 01, 2019 at 09:34 PM
Yes it is.
Make sure the to make a prefab out of the object
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; } } }
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.
there are lots of bugs also can you explain more ?
Where exactly are bugs? Apart from that, this solution unfortunately doesn't work in a game build, because the AssetDatabase class is an editor only class. The way I do it atm is to have a serialized object, keeping track of my asset relative locations (at least the ones I need to save) and then use the Resource.Load<>() function, to load them, which can be used at runtime.
Um I think your function can't work? string data; //Translate GameObject into path string assetPath = AssetDatabase.GetAssetPath((GameObject)data); Your string "data" is empty and you try to cast your empty string as a GameObject? I don't understand what you're doing there...