How to click and detect an object in Unity3D?



In this blog post, I’m sharing a simple technique and script to make you able to click any 3D object and detect what is the name of that 3D object in your Unity Editor using simple raycasting.

First of all, make some 3D objects and add a tag to them, for example “FunnyTag”. Don’t forget, after creating a new tag, make sure you re-select the object and apply the new tag.

The reason why do I need this tag is to distinct clickable objects from the other non clickable objects.

Then create a new script called TapToTouchObject.cs and copy and paste the script below:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TapToTouchObject : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit, 1000.0f))
            {
                if (hit.collider.tag == "FunnyTag")
                {
                    Debug.Log("I am changeable! My name is " + hit.collider.gameObject.name);
                }
            }
        }
    }
}

Attach this script to any object in your scene. For example an empty game object.

Run the game, then try to click those object with FunnyTag tag applied. Check the log window, and you will see that every time you click a clickable object, you will see a log text showing the name of that object.

Hope you like this post, thanks!

loading...

Leave a Reply

Your email address will not be published. Required fields are marked *