Skip to content

Instantly share code, notes, and snippets.

@ditzel
Last active May 3, 2020 18:34
Show Gist options
  • Save ditzel/b54330ae34f4fce79b71bd7412150658 to your computer and use it in GitHub Desktop.
Save ditzel/b54330ae34f4fce79b71bd7412150658 to your computer and use it in GitHub Desktop.
Detect a OnClick Event in 3D Space on a GameObject
/*
* Detects clicks on game objects
*
* 1. Attach ClickDetector component to a camera or a "game manager" object
* 2. Attach a collider (e.g. BoxCollider) to all objects that should receive a on click event
* 3. Attach a MonoBehaviour to all objects that should receive a on click event registering to the event.
*
* The MonoBehavior should have at least:
*
* public class ClickableGameObject : MonoBehaviour, ClickDetector.ClickDetectorListener
* {
* // Use this for initialization
* void Start()
* {
* Camera.main.GetComponent<ClickDetector>().AddListener(this);
* }
*
* // Update is called once per frame
* void Update()
* {
* }
*
* void OnDestroy()
* {
* Camera.main.GetComponent<ClickDetector>().RemoveListener(this);
* }
*
* public void OnClick(RaycastHit hitInfo)
* {
* //do something
* }
* }
*
**/
using UnityEngine;
using System.Collections.Generic;
public class ClickDetector : MonoBehaviour
{
/// <summary>
/// Listeners
/// </summary>
protected Dictionary<GameObject, ClickDetectorListener> listeners = new Dictionary<GameObject, ClickDetectorListener>();
/// <summary>
/// Camera the component is attached to
/// </summary>
protected Camera AttachedCamera;
/// <summary>
/// Check if connected to camera (not nessasaray)
/// </summary>
void Start()
{
AttachedCamera = GetComponent<Camera>();
}
/// <summary>
/// Check collisions
/// </summary>
void Update()
{
var ray = ((AttachedCamera!=null)?AttachedCamera:Camera.main).ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (listeners.ContainsKey(hit.collider.gameObject) && Input.GetMouseButtonDown(0))
listeners[hit.collider.gameObject].OnClick(hit);
}
}
/// <summary>
/// Add a listener
/// </summary>
/// <param name="listener"></param>
public void AddListener(ClickDetectorListener listener)
{
listeners.Add(((Component)listener).gameObject, listener);
}
/// <summary>
/// Remove a listener
/// </summary>
/// <param name="listener"></param>
public void RemoveListener(ClickDetectorListener listener)
{
listeners.Add(((Component)listener).gameObject, listener);
}
/// <summary>
/// Receiver for the on click event
/// </summary>
public interface ClickDetectorListener
{
/// <summary>
/// the game object was clicked
/// </summary>
/// <param name="hitInfo">Additional Info of the raycast from the camera to the object</param>
void OnClick(RaycastHit hitInfo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment