I’m using the unity ui buttons and the OnMouseUp or OnMouseOver functions are never triggered. I can activate the OnMouseUp when I use the “On Click ()” section in the inspector and choose the function from there.
I’ve looked through other answers first. The buttons are in a canvas, the raycast target is checked, there is an event system. Using the eventsystem I can see that indeed pointer enter and pointer press point to the correct button. Still the OnMouse… functions are never called (yes the script is also attached to the button):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseOverTest : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnMouseUp()
{
Debug.Log("on mouse up caught");
}
public void OnMouseOver()
{
Debug.Log("on mouse over caught");
}
}
4 Answers
4
I don’t know if it has to do anything with the problem but usually when I write my code, I don’t specify whether it’s public or not. Either way it shouldn’t affect it. Anyways, I digress.
The documentation says that the script must be attached to the object over which you want to move the mouse over. Furthermore, this must be either a GUIElement or a Collider.
I made a small project. I put a square in the scene and attached a box collider 2d to it. Then, I attached the following script to it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMouseController : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnMouseEnter()
{
Debug.Log ("Enter");
}
public void OnMouseOver()
{
Debug.Log ("Over");
}
public void OnMouseExit()
{
Debug.Log ("Exit");
}
}
It works fine…Are you sure you’re satisfying the documentation’s criteria?
Did the same as you, and with e.g. a 3D object with a collider it does work. But the same doesn’t work for the UI buttons. I’m wondering if it’s about the placement of the canvas…
Did the same as you, and with e.g. a 3D object with a collider it does work. But the same doesn’t work for the UI buttons. I’m wondering if it’s about the placement of the canvas…
OnMouse events only occur in objects that have a collider or in GUIElements (legacy UI system). The newer UI doesn’t generate the old-and-good OnMouse events, but you can add the Event Trigger component to the UI button and do some things when the desired events occur, including call the OnMouse functions you already had in your script - more info in the UI tutorial.
Did the same as you, and with e.g. a 3D object with a collider it does work. But the same doesn't work for the UI buttons. I'm wondering if it's about the placement of the canvas...
– elvirais