1

I would like to create a menu item that can build a game object with children and components. I can't use prefabs for the whole objects because I need that the children are separate prefabs.

1 Answer 1

4

You can use something like this:

[MenuItem("YOUR_MENU_NAME/YOUR_SUBMENU_NAME/YOUR_METHOD_NAME %&n")]
static void CreateAPrefab()
{
    //Parent
    GameObject prefab = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<Object>("Assets/Prefabs/TestPrefab.prefab"));
    prefab.name = "TestPrefab";

    if(Selection.activeTransform != null)
    {
        prefab.transform.SetParent(Selection.activeTransform, false);
    }
    prefab.transform.localPosition = Vector3.zero;
    prefab.transform.localEulerAngles = Vector3.zero;
    prefab.transform.localScale = Vector3.one;

    //Child 1
    GameObject prefabChild1 = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<Object>("Assets/Prefabs/TestPrefabChild1.prefab"));
    prefabChild1.name = "TestPrefabChild";

    prefabChild1.transform.SetParent(prefab.transform, false);
    prefabChild1.transform.localPosition = Vector3.zero;
    prefabChild1.transform.localEulerAngles = Vector3.zero;
    prefabChild1.transform.localScale = Vector3.one;

    //Child2...
    //...

    Selection.activeGameObject = prefab;
}

Don't forget to include using UnityEditor; and to either place the script in an Editor/ folder or use #if UNITY_EDITOR / #endif around the parts using the editor methods. Also I added a shortcut to the MenuItem using %&n (Ctrl + Alt + N).

If you need to change the prefabs that compose the instantiated object, you can try to retrieve them all in your project (maybe be and heavy operation depending on your project) as they did here and display a kind of checklist where you select the prefabs needed as children inside an EditorWindow.

Sign up to request clarification or add additional context in comments.

2 Comments

That's exacty what I was looking for.
Glad it helped!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.