Reputation: 21
I am having a problem where OnMouseEnter 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 OnMouseEnter()
{
rend.material.color = hoverColor;
}
}
Upvotes: 2
Views: 7184
Reputation: 1
Hope this helps
Upvotes: 0
Reputation: 31
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 OnMouseEnter()
{
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 OnMouse 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 OnMouse functions work with the Standard Raycast in all layers except layer 2
Upvotes: 1
Reputation: 61
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 OnMouseOver. 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!
Upvotes: 4
Reputation: 61
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
Upvotes: 0