AryanshDev
AryanshDev

Reputation: 90

Detect Object Click in Unity

and Working on a Project. I just wanted to know, Is There any way to detect if a GameObject is clicked ?

More precisely, To Destroy an Object when it is Clicked. i.e.

if (Object_is_clicked) {
Destroy(this.gameObject);
}

Upvotes: 2

Views: 4099

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26450

You can use the event system.

Create a MonoBehavior

using UnityEngine.EventSystems;

public class ClickDetector : MonoBehaviour, IPointerClickHandler
{
    public void OnPointerClick(PointerEventData eventData)
    {
        Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);
    }
}

Attach to the game object you want to monitor

Check here on how to do it

You can you the generic GameObject.AddComponent<Type>() to do it in runtime.

Upvotes: 4

Related Questions