Add prefab as child of another prefab

Hey all,

So I’m working on a prefab editor tool and I’m a bit stumped. I’m trying to, via script, make a pre-existing prefab a child of another prefab within my project assets. I’d prefer to avoid instantiating the prefab within the scene if possible. Basically all I’m looking to do is get an instance of a prefab and add this instance as a child of the second prefab.

I’m relatively new to modifying prefabs via script and am trying to wrap my head around how it all works. Is it possible to do something like this without instantiating the prefabs within the current scene temporarily?

Any advice and responses appreciated, thanks in advance!

Cheers

Prefab assets are just game objects, and you can find them via AssetDatabase and treat them like any other Unity object.

Would be interesting to see if you can find the specific prefab and just instantiate an object with it’s transform as the target.

Nonetheless there is prefab utility class for managing prefab assets: Unity - Scripting API: PrefabUtility

And some other useful classes:

1 Like

Thanks for the references, I wasn’t aware of PrefabStage and PrefabStageUtility

It’s interesting, I seem to be able to be able to get the child added temporarily but saving the prefab seems to be a whole can of confusing. You’d think the API would be more streamlined for this, but it seems like there’s a lot of different methods that do many variations of the same thing but with different requirements

EDIT:
It looks like they did add an easier way to modify prefabs:

Incredibly handy and simple to use

1 Like