Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to check if finger is touching UI with tags?

Discussion in 'Scripting' started by MatanYamin, Mar 23, 2022.

  1. MatanYamin

    MatanYamin

    Joined:
    Feb 2, 2022
    Posts:
    109
    Hello everyone!
    I have a question about finger touching in Unity.
    I have a UI prefab that does something when I touch it with the help of "EventSystem.current.IsPointerOverGameObject" - so far so good.
    But I'm asking myself, what if I want to recognize a specific UI object that has been touched with the help of its "tag" or "layer"?
    Because the way I use now is too generic, and if I have a few UI's then it will be impossible to use that function if every UI is doing something else when pressed on (correct me if I'm wrong).

    Hope it was clear, thanks in advance!
     
    Last edited: Mar 23, 2022
  2. SunnyValleyStudio

    SunnyValleyStudio

    Joined:
    Mar 24, 2017
    Posts:
    67
    Hey!

    I think that you will find the IPointerClickHandler useful in this situation (if you are using the default input system).

    You could create a component that either does something specific when the UI element is clicked or you can create something more universal using UnityEvents.

    This way you can easily create prefabs from your UI elements so they have the specific OnClick functionality.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.Events;
    3. using UnityEngine.EventSystems;
    4.  
    5. public class FlipOnTouch : MonoBehaviour, IPointerClickHandler
    6. {
    7.     public void OnPointerClick(PointerEventData eventData)
    8.     {
    9.         //Flip the object logic
    10.     }
    11. }
    12.  
    13. public class MoreGenericClick : MonoBehaviour, IPointerClickHandler
    14. {
    15.     public UnityEvent OnClickEvent;
    16.     public void OnPointerClick(PointerEventData eventData)
    17.     {
    18.         //You will now assign a method to the OnClickEvent
    19.         OnClickEvent?.Invoke();
    20.     }
    21. }
    upload_2022-3-23_9-22-53.png

    If you still would like to create a single Manager script to handle player movement you would still have to send the info in the OnClickEvent to this manager class and the object reference:
    Code (CSharp):
    1. public UnityEvent<GameObject> OnClickEvent;
    This way you can perform all sorts of checks of what is the tag etc.

    I hope this helps!