- Home /
How could I create a prefab from an exsisting gameobject at runtime?
I need to create a prefab from a gameobject at runtime, but without changing the gameobject. I also need this prefab to contain all children and grandchildren, unless the current prefab system already does this.
Instantiating a prefab is exactly this, as long as all chidren etc are part of the prefab. If not, you want to make a copy of object(s)?
What are you going to do with this prefab after you create it? If all you want to do is create copies of an existing GameObject subtree at runtime then you can easily do that using Instantiate - just pass it an object from the scene ins$$anonymous$$d of passing it something from a prefab.
I need a prefab, I can't use instantiate though, because I am changing the original gameobject changes, but I'd like to continue to refer to the starting state of the gameobject.
You can make copies of copies plus you can make changes after Instantiate() to the copies.
I'm fairly sure you cannot create a real prefab at runtime. At runtime there is no folder structure to put files (they've been rolled into a single-file database), and all the Edit-time support for modifying asset database is missing from the Runtime.
Answer by gfoot · Jan 15, 2014 at 11:22 PM
As others have said, I don't think it can be done exactly the way you want. I know you said you weren't interested in workarounds, but the best solution I have is making a clone of the source GameObject and parenting this snapshot under a disabled GameObject, so that it doesn't update or render. Then you can clone this elsewhere in the scene just as you would a prefab.
Answer by rutter · Jan 15, 2014 at 11:23 PM
There is no way to create prefabs in a built player. You can do it in the editor, but that doesn't seem to be what you're looking for.
I need to create a prefab from a gameobject at runtime, but without changing the gameobject.
You can certainly use Instantiate() to duplicate objects. You could disable those objects so that their state never changes. You could keep them between scenes with Object.DontDestroyOnLoad. You could use some static references to keep a "singleton" reference. In practice, that's the closest you can get to a "runtime prefab".
I also need this prefab to contain all children and grandchildren, unless the current prefab system already does this.
Prefabs contain one GameObject and all of its children (with the minor caveat that its children cannot be "nested" prefabs).
If you Instantiate() an object, the clone will contain copied children and components.