How to instantiate prefabs in edit mode and mantain instance connection

I searched a lot, found nothing. So here’s my question:

I grab the selected prefab in the project view via Selection.selectionChanged ((to check if it is a prefab, selectedObj.scene.rootCount == 0)

Then I instantiate it in the scene using my tool:

var obj = (GameObject)PrefabUtility.InstantiatePrefab(selectedObj, sceneBackup);

When dropped by hand in the hierarchy or scene, it mantains the prefab icon and the parent-instance reference. But when I do it via code, that connection is lost, and the resulting GO is not related in any way to the original prefab in the project, I can’t find a proper way to simulate the drag-drop functionality in the editor.

Are you doing this in an editor script during edit mode, or are you doing this in play mode?

Doing it in play mode won’t work, and indeed PrefabUtility will not exist if you try to build your game.

I’m assuming it’s an editor script, but it’s worth asking. PrefabUtility should definitely work in edit mode :face_with_spiral_eyes:

Yes, it’s edit mode. It doesn’t mantain the linkage. No prefab icon, it becomes a regular GO.

Ok. I tried a little tool to test this. It worked correctly.
Then moved the code to my original code, and worked… then removed everything and used my previous code, and works correctly.

Maybe this was something that was fixed and I didn’t noticed.
So it works, yes!

1 Like