Skip to content

ThirteeNov

My personal blog about coding and internet

Menu
  • About me
  • About Zofia Kreasi
  • Cart
  • Checkout
  • Making an airplane game from scratch in Unity
  • My account
  • Privacy Policy
  • Privacy Policy – zkLeaderboard
  • Sample Page
  • Shop
  • Tutorials on Learning JavaScript
  • ZKAccounts – Privacy Policy
Menu

How to click and detect an object in Unity3D?

Posted on January 27, 2022January 27, 2022 by Habibie

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!

Post Views: 362
ciihuy2020

Welcome!

  • My YouTube Channel
  • My GitHub Page
  • About me

Categories

  • 3DVista
  • Android
  • Apache
  • C#
  • Cordova
  • Electron & Node JS
  • HTML5, CSS & JavaScript
  • iOS
  • Let's Make Unity Games
  • Misc
  • Photoshop
  • PHP
  • Python
  • Uncategorized
  • Unity
  • WordPress

Recent Posts

  • Make objects like wires and cables easily in Unity using Ciihuy Curved Mesh
  • [SOLVED] Can’t Add Custom Domain to Blogger After Losing CNAME Verification
  • iOS App Icon Generator by CiihuyCom
  • Advanced Blinking Marker Script to show objects position in your game canvas
  • Ciihuy Images Merger – Fast & Easy Online Image Combiner
© 2025 ThirteeNov | Powered by Superbs Personal Blog theme