UI Script that generates an object at mouse position

Hi,

I’ve been trying to write an editor script that would instantiate a prefab to the scene with a key command, to selected mouse position.

The idea is that you can point an object in the scene edit view and press, say, shift-d and that would generate an object that is aligned to the object below the mouse cursor.

So far I’ve managed to make the menu command but I’m facing three problems that I haven’t yet found a solution to:

The first problem is that I haven’t found a way to get the mouse coordinates in the scene edit view so that I could cast a ray into the scene. If the game view is active, menu commands don’t seem to work.

The second problem is that because the AddObject() menu command I made has to be static, I don’t know how to do an editor view for selecting the prefab I want to instantiate, but have to use Resources.Load() instead (works, but it’s an ugly solution).

Third problem is that the script does not seem to run all the time even if ExecuteInEditMode is set, which makes the whole thing completely useless :slight_smile:

Any help would be appreciated!

using UnityEditor;
using UnityEngine;

[ExecuteInEditMode]


class MenuTest : Editor 
{
  [MenuItem ("GameObject/AddObject #d")]
  static void AddObject() 
  {
    // Seems to return invalid value in scene view
    Debug.Log(Input.mousePosition);

    // ... so this doesn't work
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		
    // Object = layer 9		
    int layerMask = 1 << 9;
		
    // Get object that I want to instantiate
    GameObject what = (GameObject) Resources.Load("Prefab_Grass_Hard_01", typeof(GameObject));

    if (!what)
    {
      Debug.Log("not found");
    }
    else
    {
      Debug.Log("found");
    }

    // Snap to the object
    RaycastHit hit;
    if (Physics.Raycast (ray.origin, ray.direction, out hit, Mathf.Infinity, layerMask)) 
    {
      Quaternion q = Quaternion.FromToRotation( Vector3.up, hit.normal );
      GameObject.Instantiate( what, hit.point, q );
    }
  }
}

br,
Sami

Regarding the picking problem, take a look at HandleUtility.GUIPointToWorldRay().

Camera.main references the first camera in the scene tagged as ‘MainCamera’; it doesn’t reference the in-editor camera. It is possible to access the editor camera via Camera.current, but I’ve found that using this for raycasting doesn’t produce accurate results in the editor. The function mentioned above should work though.

Regarding mouse input, I don’t believe that the Input class runs in edit mode, in which case you won’t be able to get the mouse position that way. In (e.g.) OnSceneGUI(), you can get the mouse position using Event.current, but I’m not sure how you would acquire it in a function invoked via a menu command. Maybe someone else can comment on this.

I didn’t quite follow the other problems described in your post, but if you want to be able to select the prefab to be cloned interactively, I’d think you’d want to use some sort of interactive interface, such as a wizard or editor window.

Hmm, looks like this translates a 2d GUI point to a ray, but the big question still remains - how the heck do I get the 2d coordinate for the mouse in scene view window?

Or is there some way of getting the mouse position from the window where cursor currently is? At least I haven’t found one that would work inside a menu command…

Yeah, could be. I was first thinking of just putting the prefab in the code like usual (so that I could change it in the same way as you assign prefabs in normal code)

public GameObject objectToInstantiate;

but this of course doesn’t work because I’d need an instance of the class running somewhere, and I’d need a way for the static menu command to have access to it.

Changing it to static doesn’t let me select the prefab (as it is no longer displayed under “default references”) in the monoscript’s inspector:

public static GameObject objectToInstantiate;

Getting a bit difficult… Maybe I do need to write a custom editor window for this.

br,
Sami

Regarding the mouse coordinate problem, take a look at Event.current.

Seems to be NULL if you access it inside a menu command?

br,
Sami

OK, this part seemed to be easy… I got a window with an object field up’n’running.

By the way, the reason why I wanted the script to execute in edit mode was that it would be cool to interactively be able to see the object in the screen before placing it (ie, shift-d would instantiate the object, and it would snap to whatever your mouse cursor is over at the moment, and then shift-f or something would drop it into the scene).

br,
Sami

Right, Event.current would be for OnSceneGUI() and so forth.

I’m not sure how to get the mouse position within a function invoked via a menu command (aside from writing it to a variable in a function that does have access to it, or something equally convoluted). Maybe someone else can answer that question.

Yeah, exactly… The problem is that OnSceneGUI() is not called even if ExecuteInEditMode is set… Take a look at my current code:

using UnityEditor;
using UnityEngine;

[ExecuteInEditMode]

class MenuTest : EditorWindow
{
	// The object
	public static GameObject objectToInstantiate;
	
	// Shows the menu
	[MenuItem ("GameObject/ShowMenu #s")]
	static void ShowMenu() 
	{
		MenuTest window = (MenuTest) EditorWindow.GetWindow (typeof (MenuTest));
	}

	// Drops the item
	[MenuItem ("GameObject/Drop Item #d")]
	static void DropItem() 
	{
		PlaceObject();
	}
	
	/**
	 * Picker GUI
	 */	
	void OnGUI () 
	{
		GUILayout.Label ("Select the thing to clone", EditorStyles.boldLabel);
		objectToInstantiate = (GameObject) EditorGUILayout.ObjectField("Clone me", objectToInstantiate, typeof(GameObject));
	}	
	
	/**
	 * Places the object
	 */
	static void PlaceObject()
	{
		Ray ray = Camera.current.ScreenPointToRay(Input.mousePosition);
		//Ray ray = HandleUtility.GUIPointToWorldRay( ??? );
		
		// Object = layer 9
		int layerMask = 1 << 9;
				
		// Snap to the object
		RaycastHit hit;
		if (Physics.Raycast (ray.origin, ray.direction, out hit, Mathf.Infinity, layerMask)) 
		{
			Quaternion q = Quaternion.FromToRotation( Vector3.up, hit.normal );
			GameObject.Instantiate( objectToInstantiate, hit.point, q );
		}
	}
	
	/**
	 *
	 */
	void OnSceneGUI()
	{
		Debug.Log(Event.current);
	}
}

So, looks like camera.current.ScreenPointToRay() does not work (gives a null reference exception), and OnSceneGUI() never gets called… Hmm hmm.

br,
Sami

OK,

Here’s my best bet so far … Seems to work decently, though I’d still like to find a way for faster update rate:

EDIT: interestingly enough, the gizmo (the green line) updates much faster if I select any particle system in the scene… Uh oh :smiley:

using UnityEditor;
using UnityEngine;

class MenuTest : EditorWindow
{
	// The object
	public static GameObject	objectToInstantiate;

	// The place to put the obj
	public	static	Vector3		placePos;
	public	static	Quaternion	placeRot;

	// Show window
	[MenuItem ("GameObject/Show Window #s")]
	static void ShowWindow() 
	{
		MenuTest window = (MenuTest) EditorWindow.GetWindow (typeof (MenuTest));
	}
	
	// Place the object
	[MenuItem ("GameObject/Drop Item #d")]
	static void DropItem() 
	{
		PlaceObject();
	}
	
	/**
	 * Picker GUI
	 */
	public void OnGUI() 
	{
		objectToInstantiate = (GameObject) EditorGUILayout.ObjectField("Clone me", objectToInstantiate, typeof(GameObject));
	}
	
	/**
	 * Places the object
	 */
	static void PlaceObject()
	{
		if (placePos != null  placeRot != null)
		{
			GameObject.Instantiate( objectToInstantiate, placePos, placeRot );
		}
	}

	/**
	 *
	 */
    [DrawGizmo(GizmoType.NotSelected)]
    static void RenderCustomGizmo(Transform objectTransform, GizmoType gizmoType)
    {
    	if (Event.current == null)
    		return;
    		
		Ray ray = HandleUtility.GUIPointToWorldRay (Event.current.mousePosition);
		int layerMask = 1 << 9;
		RaycastHit hit;
		if (Physics.Raycast (ray.origin, ray.direction, out hit, Mathf.Infinity, layerMask)) 
		{
			Gizmos.color = Color.green;
			Gizmos.DrawLine( hit.point, hit.point + hit.normal * 100.0f );
			placePos = hit.point;
			placeRot = Quaternion.FromToRotation( Vector3.up, hit.normal );
		}
    }
}

it seems that ExecuteInEditMode doesnt work in unity3, cuz I always used this tag in 2.6, everything worked fine. And now Update in script with ExecuteInEditMode is called only in some cases like when you click hierarchy screen, or reimport script and so on… and this is bad (((

well, I was mistaking in prev post :slight_smile:
take a look at this thread
http://forum.unity3d.com/threads/73769-ExecuteInEditMode-unity3