- Home /
Detect if object clicked on
I have a script to detect if an object has been clicked on but when I click nothing happens
var selectedUnits : Array = new Array();
function Update (){
if(selectedUnits.length <= 0){
if(Input.GetMouseButtonDown(0)){
var hit : RaycastHit;
Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit);
Debug.Log(hit.collider.tag);
}
}
}
Verify the script is attached to some object. Put Debug.Log() just inside all the 'if' statements to verify where the code is failing. Since you don't have an 'if' statement around the Physics.Raycast(), then the must likely culprit is "selectedUnits.length" being > 0.
You really should put an if statement around the Raycast:
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit)) {
Debug.Log(hit.collider.tag);
}
If your code is getting to the raycast but is not finding anything, verify the object you are clicking on has a collider.
Thanks for the point about needing a collider. The object I was dealing with has no physical interactions with anything else, so I removed its collider thinking it wasn't necessary.
Answer by ninjaboynaru · Mar 16, 2013 at 08:45 PM
Robertu got it right. The script was not attached to the object. Thanks for the help.
Just a point - you can just use
function On$$anonymous$$ouseDown()
{
}
On the object being hit...
Answer by Seth-Bergman · Mar 16, 2013 at 08:32 PM
if(selectedUnits.length <= 0){
how can the length be less than zero? start by getting rid of that line, and if that doesn't do it, make sure your object has a COLLIDER attached
Your answer
Follow this Question
Related Questions
Clicked object is stored in a variable? 1 Answer
Mouse Click and Spawn object 4 Answers
Spawn Objects Where i click 2 Answers
Detecting a GUI element under the mouse? 1 Answer
Getting raycasting info from mouse event (eg through RaycastHit) 0 Answers