- Home /
Instantiate a prefab at the Mouse's position?
I have been trying to instantiate a prefab at the position of the cursor, like this:
However the when I click the prefab isn't instantiating at the exact position of the cursor, It is off most always and sometimes it won't even show up in front of the camera.
my code is:
function Update () {
var MousePosition = Input.mousePosition;
if (Input.GetMouseButtonDown(0))
{
var ObjectPosition = Camera.main.ScreenToWorldPoint(MousePosition);
ObjectPosition.y = 0;
Instantiate(Object, ObjectPosition, Quaternion.identity);
}
}
This script is attached to the Main Camera if that helps any. I am trying to instantiate the prefab on a plane, also.
Answer by Piflik · Jul 16, 2012 at 01:26 PM
ScreenToWorldPoint(MousePosition) doesn't necessarily give you the coordinate you want (but since your question is a bit vague, I don't exactly know what you want...the mouse position is generally in 2D, while the world is 3D...do you want to spawn the object on a terrain?)
I'd use a raycast and instantiate the object on the intersection of the ray and whatever plane the object should sit on.
Well, I'm no expert with Unity and I have no experience with Rays, What would you suggest I do? If you can't point me to a specific API reference, could you give me an overview of what I should do?
This raycast would hit only objects on the 8th layer (that's what the layer$$anonymous$$ask is doing) and instantiate the object at the intersection. You need a $$anonymous$$ain Camera, but there is one by default, so if you didn't delete or retag it, it should be there. If it isn't there, you'd need to find the camera you are using a different way, probably by assigning it via the Inspector.
private var layer$$anonymous$$ask = 1 << 8;
if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), mousPos, $$anonymous$$athf.Infinity, layer$$anonymous$$ask)){
Instantiate(Object, mousPos.point, Quaternion.identity);
}
Further information can be found in the script reference.
Well I have this now and it isn't even instantiating the transform at all.
This is my code
function Update () {
var hit : RaycastHit;
var layer$$anonymous$$ask = 1 << 8;
if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit, $$anonymous$$athf.Infinity, layer$$anonymous$$ask)){
if (Input.Get$$anonymous$$ouseButtonDown(0)) {
Instantiate(Object, hit.point, Quaternion.identity);
}
}
}