- Home /
How can I only instantiate if mouse over?
I am working on a game where I have a particle system prefab that instantiates on MouseButtonDown but I only want it to instantiate if the mouse is over a clickable object. I need to have the script on the camera so I believe I need to use raycasting but can't work out how to do this. Here is the code I have. How would I go about making this script work only when over my object? Any help would be much appreciated!
var box : Transform;
function Update ()
{
if (Input.GetMouseButtonDown(0))
{
var mousePos : Vector3 = Input.mousePosition;
mousePos.z = 10.0;
var worldPos : Vector3 = GetComponent.<Camera>().ScreenToWorldPoint(mousePos);
Debug.Log("Mouse pos: " + mousePos + " World Pos: " + worldPos + " Near Clip Plane: " + GetComponent.<Camera>().nearClipPlane);
clone = Instantiate(box, worldPos, Quaternion.identity);
}
}
Answer by Cherno · Jul 19, 2015 at 08:18 PM
Indeed you can use RayCasting. Take a look at the Scripting API for Input.mousePosition; it has an example.
You have to attach a collider to the GameObject you want to click on.
var box : Transform;
function Update ()
{
if (Input.GetMouseButtonDown(0))
{
var mousePos : Vector3 = Input.mousePosition;
mousePos.z = 10.0;
var worldPos : Vector3 = GetComponent<Camera>().ScreenToWorldPoint(mousePos);
Debug.Log("Mouse pos: " + mousePos + " World Pos: " + worldPos + " Near Clip Plane: " + GetComponent<Camera>().nearClipPlane);
Ray ray = GetComponent<Camera>().ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast(ray)) {
clone = Instantiate(box, worldPos, Quaternion.identity);
}
}
}
Also take a look at the Scripting API for Physics.Raycast and Ray for information about using LayerMask etc. so you have more control over what your ray can hit. Note that the GetComponent() function needs no "." after the GetComponent. I corrected it in my sample code.