2

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);
}

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Will it work in case of touch controls too (i.e. On Mobile Devices) ?
Yes it does. It's either click from a mouse or a touch from a screen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.