Reputation: 90
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
Reputation: 26450
You can use the event system.
using UnityEngine.EventSystems;
public class ClickDetector : MonoBehaviour, IPointerClickHandler
{
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);
}
}
Check here on how to do it
You can you the generic GameObject.AddComponent<Type>()
to do it in runtime.
Upvotes: 4