I'm trying to make a quick editor script that replaces the children of a selected object with a prefab.
How can I link the instantiated objects to the original prefab?
I'm trying to make a quick editor script that replaces the children of a selected object with a prefab.
How can I link the instantiated objects to the original prefab?
Had the same problem and just found the answer:
Use PrefabUtility.InstantiatePrefab() to instantiate the objects.
Read the documentation for the Prefab functions in the `EditorUtility` class:
You should be able to figure something out to solve your problem.
edit
Unity moved the InstantiatePrefab method into a seperate class some time ago. You have to use PrefabUtility.InstantiatePrefab now
Just an updated answer on this, as Unity updated their prefab system:
//Get path to nearest (in case of nested) prefab from this gameObject in the scene
string prefabPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(gameObject);
//Get prefab object from path
Object prefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(Object));
//Instantiate the prefab in the scene, as a sibling of current gameObject
PrefabUtility.InstantiatePrefab(prefab, transform.parent);
PrefabUtility.InstantiatePrefab returns null when I pass it a prefab from AssetDatabase.LoadAssetAtPath. Not sure if this is a recent bug, but happens in Unity 2017.4 or newer