- Home /
Detecting that I'm clicking a unit even though I'm not?
I'm working on a Turn Based Strategy game and have an issue.
Here is what the game looks like right now with 2 enemy units and one of my own units that I bought from the base (currently the purple sphere. Yay placeholders!) http://i.imgur.com/SiDyfdG.png
In my script, during Update, I call this segment of code:
//if player left clicks on a unit
if (Input.GetMouseButtonDown(0)
&& Physics.Raycast(ray, out hit, 500f, gameControl.getUnitLayer()))
{
Debug.DrawRay(ray.origin, ray.direction, Color.white, 100f);
selectUnit(hit.collider.gameObject);
}
Now here is the exact same scene shown above, but with the camera only showing layer 11, "Units" http://i.imgur.com/zUqcDAE.png
Yet the code segment is running every time I click the mouse, even if I'm very obviously not hitting anything on the units layer.. Here's a picture in the scene view of some of the draw rays, clearly not hiting any of the 3 units: http://i.imgur.com/DNJR3AV.png
Lastly, in other areas of the code, I have the information as follows. The values ARE NEVER CHANGED.
Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);
private const int unitsLayer = 1 << 11;
And that's all the information. So why is it detecting the raycast every time I click the mouse, even if I'm not clicking on a unit???
The drawray only draws if your raycast comes back true. There is a problem with the ray itself, or the layer.
Really it should not make a difference but try
Ray ray = mainCam.ScreenPointToRay(new Vector3(Input.mousePosition,0));
The z position is ignored but the function still requires a Vector3. Ive added 'new Vector3(' as that is given in the exaple in the docs.
Nope, did not help anything :/ Had to do it this way, but still, no change.
ray = mainCam.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y,0));
Do what does
Debug.Log(hit.collider.gameObject.ToString());
say?
gives me the name of the gameobject/unit that is being selected even though I'm not clicking on it. For some reason, although i have two different placeholder units, the issue is ONLY there for one of the two
Is your raycast hitting a trigger? You can turn off raycasts hit triggers in the physics section.