Here’s my code:
#pragma strict
var leftClickedObject : GameObject = null;
var layerMask : LayerMask;
function Update ()
{
if (Input.GetMouseButtonDown(0))
{
leftClickedObject = GetClickedObject();
if (leftClickedObject != null)
{
leftClickedObject.SendMessage("OnLeftClick", null, SendMessageOptions.DontRequireReceiver);
}
}
}
function GetClickedObject(): GameObject
{
var clickPosition : Vector3 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var hit : RaycastHit2D = Physics2D.Linecast (clickPosition, clickPosition);
if (hit != null && hit.collider != null)
{
return hit.collider.gameObject;
}
else
{
return null;
}
}
I’m currently using this code to test left mouse clicks in Unity. I have a 2D background and foreground, which are both sprites, with scripts attached that are supposed to display some text in the console when they are clicked.
Both are on the same sorting layer and the foreground’s order in layer is set to 1 (background at 0). The problem I have is that clicking the foreground, which sits over the background, is detected as a click on the background by unity. Clicking the background directly works fine.
Changing the Z depth of the foreground to be in front of the background solves this issue, but that seems to be against the point of being able to work with layers. Changing the sprites to be on different sorting layers does not work either - not that that would be a desirable solution.
Does anyone have any idea how to make this work using the built in layer system?
Thanks very much!
Romano
Edit: What would be great is a way of returning ALL of the sprites underneath where you’ve clicked