Making a Object Clickable in code
Updated 2 years ago
Using the Input Interfaces
When we want to make a GameObject clickable, an easy solution would be to use a Event Trigger Component. But if you like me, prefer to use code, you would try to use Interfaces.


To use any of this interfaces, you must have:
  • A Physics Raycaster component in the camera that will receive the input.
  • A EventSystem object, can be created in GameObject -> UI -> EventSystem.


This interface handles the simple click event.
//Here you declare that your object has a interface //There is no limit for how many Interfaces your class implement. public class ClickHandler : MonoBehaviour, IPointerClickHandler { //This event will show in the inspector public ClickEvent pointerEvent; //The interface forces you to implement this method //It will be called when you click in the object that holds this component public void OnPointerClick(PointerEventData eventData) { //This will call every event registered, from inspector or by code pointerEvent.Invoke(eventData); } } //ClickHandler //The UnityEvent<T> class is abstract, can't be used to instantiate objects //To use, you must implement the class first //If you want the event showing in the inspector, just be public won't be enough // you need to make it Serializable too. [Serializable] public class ClickEvent : UnityEvent<PointerEventData> { };
If you want to register for the event from another object you could do:
//Function to call //Must have the same parameters, pData could be any name, but must be a PointerEventData. void foo(PointerEventData pData){} void Start(){ FindObjectOfType<ClickHandler>().AddListener(foo); }

Other interfaces related to mouse/touch

IBeginDragHandler, IDragHandler, IEndDragHandler

Detects drag events with mouse or touch.
These 3 interfaces MUST be implemented together or the event won't trigger.'
public class DragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { Vector3 dragStartPosition; Vector3 dragStartTime; //Called when a drag start is detected public void OnBeginDrag(PointerEventData data) { dragStartPosition = data.position; dragStartTime = Time.time; //Do your stuff } //Called everyframe while the user keep the click public void OnDrag(PointerEventData data) { } //Called when the user releases the Finger/Mouse Button public void OnEndDrag(PointerEventData data) { var dragEndPostition = data.position; var deltaPosition = dragEndPostition - dragStartPosition; //Do your stuff } }


For more information of what you can get from this data object take a look in:
Maikeu Locatelli
Hobbyst - Programmer