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.