I’ve only been using Unity for a couple weeks, so forgive me for a newbish question. How does one use an Input Field to store text entered by the user? I’ve been trying for hours to figure this out. I’ve found lots of old examples, but the UI system seems to have changed recently.
In the Inspector, I can see the Text property of the Input Field update in real-time as I type it in in Game mode. And when I click outside the box to remove focus, I can generate a Debug message indicating the user is done editing (using the OnEndEdit field of the Input Field, which is linked to the parent’s script). But I can’t store this Text property! I do stuff like:
But textMessage ends up being blank – even though I see text in the Text property in the Inspector. Can someone tell me what I’m doing wrong? Also, I’ve read that maybe the legacy Input Field works better than the TMP one, but I have the same problem with both. Thanks in advance.
Thanks for your reply! I got it working! I think my problem was indeed the TMP version of Input Field. I tried again with the legacy version, and magically it worked right away.
I’m now happily storing that text in a static variable. Indeed, your point about the local variable is well taken, since the whole point of the tutorial is to learn persistence.
Also, I realized that all my fancy code for firing off my little Debug.Log() output was unnecessary. All I had to do was write the Debug.Log method, stick it in a script in a parent object, link that script to the Input Field, and set the Input Field’s OnEditEnd field to trigger my Debug.Log() method. That method seems to be all the code I need to grab the text from the Input Field. That’s a relief!
Hey, I was wondering if I can get a basically version of your code? I’m wanting to make a text adventure game with the text input, but I’m not sure how to get it running properly.
All of the input code for a text adventure will be EXTREMELY tightly tied to your UI experience, design decisions you must make such as:
does this input field become a text field after each input and scrolls up the page?
is it fixed in place?
is the text copied over to a scrolling text area that continues up the screen?
something else?
If you don’t have answers to the above, all the example code in the world won’t help you at all because decisions above will dictate which of the myriad callbacks you will listen to on the InputField.
Your best bet is to start with UI tutorials and get an InputField going and spit the typed-in text out to Debug.Log()
Until you have that, no amount of random example code is going to improve your life.
And this is just the trivial input stuff.
Parsing some text adventure input syntax is a FAR harder and more interesting task, so hurry and get some kind of input system down so you can start on the Good Stuff™.
This is an excellent approach: one step at a time.