Creating an object on the level at the mouse position

I have an overhead view and I wanted to find a way to create an object at the position of the mouse when you right click.

In the following code, var ‘curzer’ is set to a small cube directly in front of the camera. It’s like, 0.05 scale. I was using it to test to see where it ended up…if it was off of the camera I pretty much marked it as a failed experiment. I was also going to use it as the position for a Raycast, but I can’t seem to get it to show up in the right spot.

I tried the following code to put it on my mouse cursor (hence the name ‘curzer’), but I don’t think it’s going to work due to the difference in 2D and 3D in this situation…

function OnGUI ()

{
var e:Event = Event.current;
var curzer = GameObject.Find(“CursorDudley”);

 if (e.type == EventType.MouseDown && e.button == 1)
 {
	 var mCam = Camera.main;
	 var taks = Screen.currentResolution;
	 curzer.transform.position.x = mCam.transform.position.x;
	 curzer.transform.position.y = mCam.transform.position.y;
	 curzer.transform.position.z -= 3.2;
	 taksWidthMid = taks.width / 2;
	 taksHeightMid = taks.height / 2;
	 if (e.mousePosition.x < (taksWidthMid)) {curzer.transform.position.x -= (taksWidthMid - e.mousePosition.x);}
	 if (e.mousePosition.x > (taksWidthMid)) {curzer.transform.position.x += (e.mousePosition.x - taksWidthMid);}
	 if (e.mousePosition.y < (taksHeightMid)) {curzer.transform.position.y -= (taksHeightMid - e.mousePosition.y);}
	 if (e.mousePosition.y > (taksHeightMid)) {curzer.transform.position.y += (e.mousePosition.y - taksHeightMid);}
	 //if (e.mousePosition.y < (taksHeightMid)) {curzer.transform.position.y -=	 	 	 
	 
 }

Basically that was supposed to position the cube slightly under your camera and then offset him by your mouse position, but it’s not working…I think it’s because 2D can’t be easily translated into 3D like that…(2D uses pixels and 3D doesn’t, right?)

So, any suggestions on other ways it could be done or how to improve this code?

You can translate from 2d to 3d using this function: Camera.ScreenToWorldPoint(insertMousePositionHere)

And from 3d to 2d using this function: Camera.WorldToScreenPoint(insertTransformPositionHere)

You can cast a ray from the mouse pointer down to the ground, and place the curzer at the hit point (if any):

var curzer = GameObject.Find("CursorDudley");

function Update(){
    // cast a ray from the mouse pointer
    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    var hit: RaycastHit;
    if (Physics.Raycast(ray, hit)){ // if mouse pointer hit the ground
        curzer.transform.position = hit.point; // place curzer at the hit point 
    }
}