- Home /
How to detect Mouse Events when the object is coverd by another object?
For example, I have put Sphere B on Cube A.
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?
According to my knowledges, u should use Layers. But I know the only way to do this with Physics.RayCast(). In this case you have to implement On$$anonymous$$ouseOver() by yourself. If it fits you I can help with code. Hope somebody has better way.
Answer by Jiro-Ng · Mar 07, 2014 at 07:51 AM
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;
}
}
}
Your answer
Follow this Question
Related Questions
"E" to grab an object... 3 Answers
How to make object clickable when user enter collider ? 0 Answers
Changing a material with a mouse click 2 Answers
MouseOver different Objects C# 1 Answer