Detecting what object was clicked

I’m having this trouble guys,I want to make my game recognize which object the player clicked.Is there a function that can do this?

An excellent example of this is in the documentation:

var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, 100)) {
    print ("Hit something");
}

Although that doesn’t actually tell you which one you hit. For that you need to include the RaycastHit variable inside the call like so:

Physics.Raycast (ray : Ray, out hitInfo : RaycastHit, distance : float = Mathf.Infinity, layerMask : int = kDefaultRaycastLayers) : boolean

The above is the function you’ll be using. The actual implementation is:

var myCast : RaycastHit;
var rayLength : float = 300;
var objectHit : GameObject;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), myCast, rayLength)) {
    objectHit = myCast.collider.gameObject;
}

Thank very much guys:smile:

You could use “function OnMouseOver” and “function OnMouseExit” also, it would look something like this:

//is the mouse on us?
var mouseIsOver : boolean;

function OnMouseOver () {

mouseIsOver = true;

}



function OnMouseExit () {

mouseIsOver = false;

}

function Update () {

if(mouseIsOver  Input.GetMouseButtonDown(0)) {

//the code for what you want to do when the player clicks the object would go here

}

}
1 Like

I’m feeling very dumb right now…so many different implementations…

Raycast is your best option.

If you have any intentions of using iOS, use the Raycast and learn it early.

Use raycasting. The mouseover script must be local to the object being moused over, which means in a program with say, one hundred objects to click on, you’ll have to put that script on every object. However, with the raycast, you can put the script on your camera or whatever, and it will work, regardless of how many objects in your game.

With gargeraths code, add

print (myCast.collider.gameObject.name); to line 6 if you want a quick output in the console of what object you have clicked on.

Haha sorry I confused you

It’s never even occurred to me to use OnMouseOver with colliders. Could be a good thing for making targeting!