- Home /
Unity Editor Inspector creating gameObjects in world
Hi there,
I've tried and failed many times to get a working script for this.
I basically want to be able to select prefabs and drag them into the Inspector, I have about 8 objects that need to be dragged into the inspector, once that is done, I need to select the starting point of where to instantiate obj1 (Ex: -5, 0, -5)
Then on I will figure out where the rest of the objects should go depending on where the 1st obj was created, I will do the math, however I cannot get the inspector to work with my own "First object: (Drag and drop here/prefab)" for some reason I can do labels etc. But can never get an object to drag into the inspector...
How do I go about this please help.
Thanks
Answer by C.Malcolm · Feb 17, 2014 at 11:21 AM
I actually wrote an Editor script which allows the user to drag and drop a prefab into a selector, then input its position, give it a name and place it. Here is the code for that:
using UnityEngine;
using System.Collections;
using UnityEditor;
public class CustomWindow : EditorWindow {
GameObject obj = null;
Vector3 vec3 = new Vector3(0,0,0);
string objname = "";
GameObject tempobj = null;
[MenuItem ("Window/My Custom Window")]
static void ShowWindow () {
EditorWindow.GetWindow(typeof(CustomWindow));
}
void OnInspectorUpdate () {
Repaint ();
}
void OnGUI()
{
obj = EditorGUILayout.ObjectField("Select game object to place",obj, typeof(GameObject), true) as GameObject;
vec3 = EditorGUILayout.Vector3Field("placement position:", vec3);
objname = EditorGUILayout.TextField("Name for new object: ", objname);
if (obj && objname != "") {
if (GUILayout.Button( "Add to scene"))
{
tempobj = (GameObject)Instantiate(obj, vec3, Quaternion.identity);
tempobj.name = objname;
}
} else {
EditorGUILayout.LabelField ( "You must select an object and give it a name first");
}
}
}
That's a good place to get started, then I suggest reading our 'Extending the Editor' docs page:
http://docs.unity3d.com/Documentation/Components/ExtendingTheEditor.html
You should be able to add some code that then places the rest of the objects in the order you choose within the OnGUI() function.
I hope this answers your question somewhat!
Answer by MakeCodeNow · Feb 15, 2014 at 08:15 PM
I assume you already have a custom Editor subclass? If not, you'll need one. From there, take a look at the DragAndDrop docs. You'll need to check for Drag events in OnInspectorGUI and handle them correctly when the drag/drop is over your inspector.
You can also just make a List of GameObject's in your MonoBehavior, in which case Unity will do all of the editor drag-and-drop for you in the default inspector.