- Home /
UI Image and OnMouseDown not working
I made an UI Image as button and I use a script for click:
void Start() {
}
void Update() {
}
void OnMouseDown() {
Application.Quit();
}
UI Image has the script.
Do you have a collider on the UI element? This is necessary for the On$$anonymous$$ouseDown method to capture the event of the click.
You could use buttons ins$$anonymous$$d, remove the text from the button and replace its default source image with the image you want and scale to the appropriate size. After that, you can simply use the default OnClick function built directly into the button to call the function you want
Please don't include empty functions, such as start and update.
Answer by Free Arm Studios · Oct 12, 2015 at 07:45 AM
I was literally just experiencing this same problem. I found that if I put a Button component on it, that'll fix it right up.
Answer by NateJC · Dec 20, 2016 at 04:38 AM
For UGUI UI objects, instead of OnMouseDown, use OnPointerDown:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems; // Required when using Event data.
public class ExampleClass : MonoBehaviour, IPointerDownHandler // required interface when using the OnPointerDown method.
{
public void OnPointerDown (PointerEventData eventData)
{
Debug.Log (this.gameObject.name + " Was Clicked.");
}
}
Alternatively, this can also be handled in the Inspector by adding an Event Trigger component.
After two days struggling with the problem, I would just like to stress the ease and satisfaction of adding an Event Trigger component to the game object. (I had seen this answer but not acted on it because it didn't sink in).
To expand a bit: Add component > Event > Event Trigger; Add a new event (I added Pointer Click); Click on the + button, then drag the object into the GameObject Slot In my case, the same object as I was adding the Event Trigger component to); Click on the "No Function" field to choose a function that will be called on clicking, which will be the On$$anonymous$$ouseDown() function on the script that wasn't working before you added the Event Trigger component.
Answer by xarlybyte · Apr 06, 2020 at 10:06 AM
,you need a object whit a Event System component. Graphiic raycaster added to your canvas and raycast target enabled on your ui element you wanna the click