How to detect Mouse Events when the object is coverd by another object?

For example, I have put Sphere B on Cube A.

alt text

Then I add a script to Cube A, where the script is used for detecting onMouseOver and onMouseExit.


bool 	isMouseEntered  = false;
void OnMouseOver ()
{
		Debug.Log ("Enter");
		isMouseEntered = true;
}
void OnMouseExit ()
{
		Debug.Log ("Exit");
		isMouseEntered = false;
}

However, when I play the scene and move mouse around, I cannot get an OnMouseOver event but an OnMouseExit event when mouse is pointing over Sphere B.

What can I do so that I can receive OnMouseOver event even if there were many game objects covered my Cube A?

Two way to solve this.

First, you set the Sphere layer to IgnoreRayCast. With this, the MouseOver function will ignore the sphere object. This method is simple but you will not able to use MouseOver on the sphere anymore.

Another way is using Physics.RaycastAll instead of MouseOver.

void Update () 
	{
		RaycastHit[] allHit = Physics.RaycastAll(Camera.main.ScreenPointToRay(Input.mousePosition));
		foreach(RaycastHit hit in allHit)
		{
			if(hit.collider.gameObject.name == "Cube A")
			{
				//do something here
				break;
			}
		}
	}