- Home /
UI Image doesn't react to OnMouseDown()
When I use a 2D sprite the script works, when I use it on the UI Image it doesn't. Does anyone know why?
I think it is because the polygon collider 2d doesnt reconize the UI image, and it reconizes the sprite. Don't know why even though it's the same image.
And the reason why I use the canvas and UI Images its because I'm making a 2d android app.
Do you guys know a solution?
Answer by Ashokkumar-M · Jun 29, 2017 at 06:02 AM
You can Add EventTrigger Component to the Image and link it to OnMouseDown() method in the inspector with PointDown Event. Also don't forget to add EventSystem object in hierarchy. @Sharckan
I couldn't use On$$anonymous$$ouseDown() because I'm making an Apk, what I did was changing all the IU Images to 2D sprites. Anyway, I hope your answer helps someone. Thx
Check if there's an Event System in your scene, otherwise Inputs will not work.
- When you create a Canvas it automatically creates an gameobject called Event System that will handle interaction
Answer by icecold043 · Mar 28, 2019 at 07:19 PM
Hey everyone i know it's been a while but i am asking a question. The event trigger will not work for me because I am making a game where you can control two player and i don't think the event trigger can switch to another gameobject when Im hitting for exemple "Left Ctrl". So is there anyway i can do this ? I made a script before but the OnMouseDown doesn't work on a UI object, sooo, help me please ^^ Here is my script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArrowLeft : MonoBehaviour
{
[SerializeField] GameObject[] PlayerT;
public GameObject PlayerG;
public float speed = 6f;
Rigidbody2D rb;
bool Player1Playing = true;
public void Start()
{
PlayerG = PlayerT[1];
}
public void Update()
{
if (Player1Playing == true)
{
PlayerG = PlayerT[0];
}
else if (Player1Playing == false)
{
PlayerG = PlayerT[1];
}
if (Input.GetKeyDown(KeyCode.LeftControl))
{
Player1Playing = !Player1Playing;
}
//This was a test/ if (Input.GetKey(KeyCode.T))
{
// This was a test/ PlayerG.transform.Translate(Vector2.left * speed * Time.deltaTime);
}
}
public void OnPointerDown()
{
PlayerG.transform.Translate(Vector2.left * speed * Time.deltaTime);
}
}
Answer by sarveshsvn · Mar 09, 2020 at 11:51 AM
I was facing the same issue. You need to implement interface,IPointerDownHandler.
StackOverflow - How to detect click/touch events on UI and GameObjects