- Home /
Make a game object in a scene into a prefab with script
Anything I try to find on this is obsolete(from 2009,2010, etc.), basically, I have a game object already in the scene for a 2-D text based game. currently, I am trying to convert the game object in the scene to a prefab while in play mode((Basically keeping the current transform(s) and all actives(true, and false) of said game object)example lets say I click a button that button runs a command to convert the current game object and all its children into a prefab) I am no good with custom editors and cannot find anything under using unity; am I overlooking something or can you not make a game object into a prefab while running
what I'm trying to do in a sense
public GameObject = ExampleObject; public GameObject = ExamplePrefab;
convert ExampleObject to Prefab, set example prefab to equal prefab(i know how to do that last part)
then ill put an OnClick for destroying the game object and instantiate the prefab
this is a very rough example and not to the entirety but I hope it was a decent enough example.
As far as i know this is only possible in Editor so you can not do this while running your game. What you can do is create the game object while running and not destroy it when the next scene is loaded.
Answer by Deathdefy · Feb 12, 2019 at 07:25 PM
Once you enter playmode there is no longer the concept of a "Prefab". Once everything is compiled they are compiled down to objects. If you want to instantiate a new version of that same object, you can just store off that object into a GameObject in your script and instantiate that.
private void Test()
{
GameObject objToSpawn = objectIWantToCopy;
GameObject newInstanceofSpawn = Instantiate(objToSpawn);
Destroy(objectIWantToCopy);
}
That would do what you want only at runtime. Once you uncheck play, this gets destroyed because it was created at runtime. You could look into ExecuteInEditMode as well.
https://docs.unity3d.com/ScriptReference/ExecuteInEditMode.html
This allows your script to be executed while you are in edit mode. Then you could look into using the editor tools for creating prefabs.
PrefabUtility.CreatePrefab(prefabPath, newInstanceOfSpawn);
I would 100% say your best shot at doing this is creating an editor script that will convert these objects for you. I know you said you aren't that great with them but the only way to get better is to practice creating them :).