How to change placeholder text in Unity UI using script?

21,294

Solution 1

Placeholder is just a Text component. You can change it's text by:

gameObject.GetComponent<InputField>().placeholder.GetComponent<Text>().text = "Something";

Note that GetComponent<InputField>().placeholder is a Graphic component, which is not the droid you are looking for :)

Solution 2

You could also downcast the placeholder object since Text inherits from Graphic class. Something like this will also work.

Graphic graphic = gameObject.GetComponent<InputField>().placeholder;
((Text)graphic).text = "Hello";

Solution 3

This works for me but remember to assign the placeholder gameobject to the Input Field Settings->Placeholder otherwise your get a null error.

TextMeshProUGUI placeholder = (TextMeshProUGUI)userNameInput.placeholder;

placeholder.text = "Hello";

Share:
21,294
Erik Putz
Author by

Erik Putz

Updated on July 09, 2022

Comments

  • Erik Putz
    Erik Putz almost 2 years

    For my project the default values are calculated base on an external output, these values can be changed using input fields in the new Unity UI. If the values are not changed a grey placeholder should appear after the calculation. I realy can not figure out how to change the placeholder text by script, not even find a solution anywhere. I tried this:

    gameObject.GetComponent<InputField>().placeholder = uv.value;
    

    The script is attached to the given Input Field game object. However to get the written value in the input field I use this line of code:

    uv.value = gameObject.GetComponent<InputField>().text;
    

    It works fine. Did I miss something? Some help would be appreciated, to write here is my last resort. Thank you forward!

  • Erik Putz
    Erik Putz about 9 years
    thank you, this solved it. However I had to put the value change to the update cycle. Now everything is real time :). Thank you wise jedi master.
  • Jesper Hoff
    Jesper Hoff about 5 years
    Thanks. I shocked that this is the best approach though - the text and placeholders in Unity's generated Dropdown's are identical. How .placeholder doesn't refer to a UI Text class is mind bogglingly stupid, and adds unnecessary confusion.
  • Joel
    Joel almost 3 years
    This should be the accepted answer. Though should probably cast when assigning it to the variable graphic instead.