Detect MonoBehaviour.OnMouseOver on a child GO

Hi all,

I have a parent GO that has child GOs. I want when the mouse is over on each child GO to change its material.color.

Now i have two scripts

One at the parent Go which finds its children and addComponent("ChangeColor") to each.

And in the ChangeColor script i have:

function Update () {

}

function OnMouseOver() {
    renderer.material.color  = Color.red;
}

function onMouseExit() {
    renderer.material.color = Color.black;
}

The problem is that it doesn't do anything...

The answer could lie in a number of places:

  • Your child objects may not have colliders (which are required for mouse events)
  • Your "onMouseExit" should have a captial "O" (functions are case sensitive)
  • The code which adds this component to the children may have an error which is causing the script to not be added.

You may want to use "OnMouseEnter" instead of "OnMouseOver". The difference is that "OnMouseEnter" is called once only, whereas "OnMouseOver" is called repeatedly every frame while the mouse is over the object.

You could help yourself to solve this by adding "Debug.Log" commands to check whether each function that you think should be called is really being called. Eg, you could change your ChangeColor script to:

function Start () {
    Debug.Log(gameObject.name + " ChangeColor started!");
}

function OnMouseEnter() {
    Debug.Log(gameObject.name + " OnMouseOver");
    renderer.material.color  = Color.red;
}

function OnMouseExit() {
    Debug.Log(gameObject.name + " OnMouseExit");
    renderer.material.color = Color.black;
}

Once you're sure the code is functioning properly, it's best to remove these Debug.Log messages.

hope this helps!

`onMouseExit` must be `OnMouseExit`. The object must have a collider to have this work (select the GameObject and the add the collider through Component -> Physics menu (choose the most convenient one).