How to instantiate prefabs exactly in the way as drag'n'drop does?

Hello,

I am trying to achieve exactly the same thing that happens when dragging a prefab from assets to the hierarchy. By dragging I get a blue instance with an enabled context menu item ‘Select Prefab’ and the enabled menu item ‘GameObject/Apply Changes To Prefab’ after changes have been done.

My code so far is:

public static class MenuItems
{
  [MenuItem ("GameObject/UI/PlayerControlBar")]
  public static void CreatePlayerControlBar(MenuCommand menuCommand)
  {
    InstantiatePrefabByUUID<GameObject>("2442d4b1b19674f26959f32c69b751da", menuCommand);
  }

  private static T InstantiatePrefabByUUID<T>(string uuid, MenuCommand menuCommand = null) where T:Object
  {
    var prefab = AssetHelper.LoadAssetByGUID<T>(uuid);
    if (!prefab) 
      throw new Exception("Asset with UUID '" +uuid+ "' could not be loaded.");
    
    var obj = Object.Instantiate(prefab, new Vector3(), new Quaternion(), menuCommand.context as Transform);
    if(typeof(T) == typeof(GameObject) && null != menuCommand)
      GameObjectUtility.SetParentAndAlign(obj as GameObject, menuCommand.context as GameObject);
    Undo.RegisterCreatedObjectUndo(obj, "Create " + obj.name);      
    Selection.activeObject = obj;
    return obj;
  }
}

public static class AssetHelper
{
  public static T LoadAssetByGUID<T>(string guid) where T:Object
  {
    Debug.Log("LoadAssetByGUID("+guid+") | path: \"" + AssetDatabase.GUIDToAssetPath(guid) + "\"");
    return AssetDatabase.LoadAssetAtPath<T>(AssetDatabase.GUIDToAssetPath(guid));
  }
}

This works almost as expected, however, the instance in the hierarchie is a clone and not displayed in blue as well as the menus mentioned above are not enabled.

How can I imitate the same behavior like dragging the prefab into the hierarchy by a UnityEditor only script? There is no need to do it in runtime.

Prefabs are a pure editor feature. At runtime there’s no difference between a prefab and a prefab instance beside the fact that prefabs only exist in memory and not in the scene. Instantiate will simply create a clone of an object. If the source object is a GameObject the clone will be added to the scene.

If you want to preserve the prefab connection at edit time you have to use PrefabUtility.InstantiatePrefab. The PrefabUtility is an editor only class.