Search Unity

Make text appear where I clicked in 2d

Discussion in 'Scripting' started by egulick2, Dec 2, 2020.

  1. egulick2

    egulick2

    Joined:
    Oct 11, 2020
    Posts:
    5
    Hello, Im new to unity and I'm trying to make text pop up where i click in a little 2d game im making, how do I do this? Any helps appreciated, thanks.
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    There are a lot of ways, but it depends a bit on what you need it for.
    For example, you could have an already existing text object in an disabled state, and enable it when you click. But maybe you want the text to be related to something you click on.

    As a piece of general advice: divide and conquer. If a problem seems to complicated as a whole, break it down into smaller problems you can either directly solve, or easier research solutions for. From what you wrote, you will definitely want to do something on a mouse click. So that's a great place to start. Look into the input system. https://docs.unity3d.com/ScriptReference/Input.GetMouseButtonDown.html

    Now you have a way to trigger something when the mouse button is pressed down. What next? As i said, you could start by enabling an already existing gameobject which starts in an disabled state. So create your text as an object in the scene, disable it, build a reference to it into your script, and then enable the text object once the mouse button is pressed.

    You can build from there. If you need text to be specific to the item you clicked on, for example, you need a way to find out what you clicked on. Raycasts are a great way to do so. This would, for example, allow you to change the text in your text-object to the name of the gameobject you clicked on with your mouse. And so on and so forth. :)
     
    eses likes this.
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Yoreki is spot on about breaking down the problem into small digestible pieces. For example, you might try to solve these small problems one by one:
    • Detect a click
    • Detect coordinates of the mouse
    • Add a static, unchanging text element to the UI
    • Moving an existing UI element to a given screen coordinate
    • Show and Hide a UI element
    If you solve those small problems and put them all together you should be able to get your desired result.
     
    Yoreki likes this.
  4. egulick2

    egulick2

    Joined:
    Oct 11, 2020
    Posts:
    5
    Thank you! I figured it out because of this, sorry for the late response!
     
    Yoreki likes this.
  5. egulick2

    egulick2

    Joined:
    Oct 11, 2020
    Posts:
    5
    Thank you! I figured it out because of this, sorry for the late response!