Home > OS >  OnMouseEnter doesn't work when hovering over an object in Unity
OnMouseEnter doesn't work when hovering over an object in Unity

Time:01-16

I am having a problem where onm ouseEnter method doesn't really work when hovering over an object in Unity. I use Unity 2021

Here is my code:

public class Node : MonoBehaviour
{
    public Color hoverColor;

    private Renderer rend;

    private Color startColor;

    void Start()
    {
        rend = GetComponent<Renderer>();
        startColor = rend.material.color;
    }

    void onm ouseEnter()
    {
        rend.material.color = hoverColor;
    }
}

CodePudding user response:

have your gameObject a collider, it needs a collider to detect it, for example, if you have your script attached to a cube your cube will need also a box collider to detect if the mouse is over it

CodePudding user response:

If you have installed and ONLY activated the new Input System these functions WILL NOT WORK

I had installed the new Input System and learn it and then stumbled upon the section in the documentation about onm ouseOver. I was anxious to try them out but to my dismay they were not doing anything...

Since I had just installed the new Input System (and disabled the old) I wondered if that was related. Guess what... IT IS...

So if you install the Input System Package and want to activate it as well as the old Input Manager you need to set it in Projects Settings > Player > Configuration > Active Input Handling where you will have a dropdown allowing you to use either the old or the new system and also have both. I selected both. Now the mouse over triggers are working.

How this helps the next person!

CodePudding user response:

make sure your object has a collider of some kind, usually box, sphere or capsule. To automate this you can use the [RequireComponent(typeof(BoxCollider))] property, the code would look something like this.

`

[RequireComponent(typeof(BoxCollider))] 
public class Node : MonoBehaviour
{
    public Color hoverColor;

    private Renderer rend;

    private Color startColor;

    void Start()
    {
        rend = GetComponent<Renderer>();
        startColor = rend.material.color;
    }

    void onm ouseEnter()
    {
        rend.material.color = hoverColor;
    }
}

`

I can replace the BoxCollider with any other collider.

As an extra note if you need it, you can also disable these functions by moving the object to layer (2) IgnoreRaycast this way none of the onm ouse events will work even if it has a collider, it's useful if you don't want to remove or disappear the object.

gameObject.layer = 2;

since normally the onm ouse functions work with the Standard Raycast in all layers except layer 2

  •  Tags:  
  • Related