Search Unity

How can I dynamically add text to the screen during run time?

Discussion in 'Scripting' started by hazem_inspectar, Jan 14, 2020.

  1. hazem_inspectar

    hazem_inspectar

    Joined:
    Jan 10, 2020
    Posts:
    7
    Hello,

    I've been trying to integrate a game where a user can press a button and it prompts a text box that can text can be put into. However, I am completely stuck to where I can start. I've looked up different tutorials but none of them do what I want. Any help would be appreciated.
     
  2. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    Well, a button can enable and disable an object, so you could have the button enable a text object, which will cause it to appear. You can then generate what ever text you want in that text object. If you mean that you want to let the player enter text, then you can use an InputField: https://docs.unity3d.com/Manual/script-InputField.html
     
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    You want a dialog box, basically?

    Don't think of it as "dynamically adding text to the screen". I mean, you can do that by instantiating a text prefab, but that's not the best way to do a dialog box. Rather, you'd be better off building the dialog box and deactivating the GameObject; it always exists, it's just invisible until called upon.

    On that object, you'll want a script, and for the sake of ease of use, you'll want it to be a singleton. A singleton is a static [meaning global/shared by the class, as opposed to each object] reference to one instance of an object. It works a lot like the "Camera.main" reference works (which isn't quite a singleton but it's close enough), if that helps you understand it. In its simplest form it looks like this:
    Code (csharp):
    1. public class DialogBox : MonoBehaviour {
    2. public static DialogBox instance;
    3.  
    4. void Awake() {
    5. instance = this;
    6. }
    7.  
    8. public void ShowDialog(string dialogText) {
    And this specific object will be accessible from any other script in your game. So now, you can call a function on this object and pass in a string parameter, which it will use to set the .text value of a UI text object, and then show the box:
    Code (csharp):
    1.  //from anywhere
    2. DialogBox.instance.ShowDialog("Look at me, I'm a dialog box!");
    I'll leave the specific implementation details up to you, but this should get you most of the way there, and feel free to ask more questions along the way if needed.
     
    hazem_inspectar likes this.