- Home /
OnMouseDown won't work on a simple button
Hello I tried starting up unity and add this simple script to a button but it just doesn't seem to work. I tried adding the script to buttons, panel's but the console just does nothing.
using UnityEngine; using System.Collections;
public class Click : MonoBehaviour { void OnMouseDown() { print ("click"); } }
this is a simple canvas with a panel and a button on It, there's just so little I can do wrong that I don't know why it won't work
Do other log entries work on your console? Do you have log entries turned on (the little balloon icon is enabled in the top right corner of the debug console?) Is there a collider on your button? http://docs.unity3d.com/ScriptReference/$$anonymous$$onoBehaviour.On$$anonymous$$ouseDown.html
Have you defined the respective event in the inspector? You add it with the "+" option, on the list.
Answer by DoTA_KAMIKADzE · Apr 10, 2015 at 12:29 AM
You have 2 options to make it work:
1)Add BoxCollider2D to your Button and keep using MouseDown.
2)Use PointerDown:
using UnityEngine;
using UnityEngine.EventSystems;
public class Click : MonoBehaviour, IPointerDownHandler
{
public void OnPointerDown(PointerEventData eventData)
{
print("click");
}
}
P.S. Though if you don't need a particular event for button you can do that as well:
private Button buttRef;
private void Awake()
{
buttRef = GetComponent<Button>();
}
private void Start()
{
if (buttRef != null) buttRef.onClick.AddListener(() =>
{
print("click");
});
}
Just FYI.
Answer by xydroh · Apr 10, 2015 at 04:34 PM
I've stopped trying to let the OnMouseDown work and I added a script to the button with a random method in it. I used the onClick thingie in the inspector and that's how I got to the method.
Thanks for helping me
Your answer
Follow this Question
Related Questions
RaycastHit only way to do OnMouse events for colliders in Mobile? 0 Answers
2D Game Mouse Problem 0 Answers
OnMouseDown for Right Mouse 2 Answers
Do something when there is no mouse click 1 Answer
Is it possible to use OnMouseDown(collision other) ??? 1 Answer