Need help with showing a textbox describing object on click of object

Hi can anyone guide me a step by step tutorial on how to show a text on click of the object over it

Hello, I haven’t really done this kind of thing before but I do have an idea of how to get it working.

Before you start writing any code, make sure to create a script in the object you want to click, I am going to assume this is a 2D game but if not this script should work fine but instead of using Vector2 use Vector3.

Step 1:

Create a Vector2 variable called mousePos, this will be used to detect where the mouse is.

Step 2:

in the update function, mousePos = Input.mousePosition. That should work but if not you may need to make separate float variables for each x and y coordinate of the mouse by using Input.mousePosition.x etc.

Step 3:

Create a public Transform variable of the object you want to click. We can use this to detect the distance between the mouse and the target object. Once you have made the variable, in the update function you can write, if(Vector2.Distance(transform.position, mousePos) < 2){}. All this is doing is checking if the mouse position is close enough to the object.

Step 4:

Check if you are clicking, to do this just change the if statement to this, if(Vector2.Distance(transform.position, mousePos) < 2 && Input.GetKey(KeyCode.Mouse0)){}. This just checks if you are clicking or not.

Step 5:

Create an empty game object to hold your textbox in. This just makes it easier to turn all of the components within that object on and off. Once you have done that, create your text of what you want to say (the description of the object), and drag it into the empty game object you just made so that it is a child of it.

Step 6:

Go back to your script and make a public GameObject description. This will allow us to turn on and off the text game object. Now in the update function, add this to your if statement,

if( Vector2.Distance(transform.position, mousePos) < 2 && Input.GetKey(KeyCode.Mouse0) )
    description.SetActive = true;
    description.SetActive = false;

Step 7:

I’m pretty sure that should work, if not, some ways you could debug your script would be removing the Vector2.Distance check and just test if it works when clicking with the mouse.

I hope this helps with your problem, I haven’t tested this code myself so I’m hoping I’m right. Anyways, good luck.