- Home /
Using IPointerDownHandler to check what object was pressed
Hello, I have used IPointer methods before however I have only ever used them on the object which is being pressed, so I can tell which object is being interacted with. I am now implementing an interface into my project called IInteractable which will handle all interactions from the player, and there is a class called Interactable which implements this interface. I have another class called Player_Input which deals with all player input and this is where IPointer methods are used. My problem is that I need to find out what object is being pressed with IPointerDownHandler() from Player_Input so I can call the necessary methods on it if it implements IInteractable. I might not have explained very well but here are my scripts:
Player_Input
using UnityEngine;
using UnityEngine.EventSystems;
public class Player_Input : MonoBehaviour, IPointerDownHandler
{
public virtual void OnPointerDown(PointerEventData eventData)
{
//check if clicked object implements IInteractable, then call OnPointerDown on that script
}
}
Interactable
using UnityEngine;
public class Interactable : MonoBehaviour, IInteractable
{
public Interactable_Type interactableType;
public void OnPointerDown()
{
switch(interactableType)
{
case Interactable_Type.button:
Debug.Log("Button Pressed");
break;
}
}
}
So.. what you want for your code, correct me if I'm wrong, is to know which object was clicked, when you are inside the OnPointerDown method of the Player_Input class?
Answer by Kennai · Jun 07, 2019 at 08:31 AM
Hi, @KurtisWeb ! Maybe so?
Player_Input
using UnityEngine;
public class Player_Input : MonoBehaviour
{
public static void CustomClick(Interactable obj)
{
switch(obj.interactableType)
{
case Interactable_Type.button:
Debug.Log("Button pressed");
break;
}
}
}
Interactable
using UnityEngine;
using UnityEngine.EventSystems;
public class Interactable : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
{
public Interactable_Type interactableType;
public void OnPointerDown(PointerEventData pointerEventData)
{
Player_Input.CustomClick(this);
}
public void OnDrag(PointerEventData eventData)
{ }
public void OnPointerUp(PointerEventData pointerEventData)
{ }
}
p.s. You need to implement all three methods OnPointerDown, OnDrag, OnPointerUp, otherwise it wont work correctly.
CustomClick would be called from Interactable.OnPointerDown it means when you click on Interactable object, it will trigger OnPointerDown. And OnPointerDown will "invoke" Player_Input.CustomClick.