- Home /
Instantiate and edit a text box during runtime
I'm trying to make it so that users can create a text box in worldspace when they start typing on the keyboard.
So far I have a prefab containing a Text(Script) component which has all the desired text box preferences. I'm having trouble figuring out how exactly the player can access the text field in this box and edit it during gameplay. So far the closest thing I've gotten is having a separate TextArea in the GUI and then passing that string to the text in the Text(Script) component, but surely there's a better way.
Here's a screenshot to help illustrate what I've gotten so far. The TextArea is the entry field on the top left of the screen and the floating text in the worldspace is the text box whose text I want to edit during runtime.
Answer by Loui_Studios · Jan 30, 2017 at 03:56 PM
Use GetComponent() to get the Text component on the prefab.
By modifying Text.text, the text of the component will change.
A simple script would look something like this:
public GameObject textPrefab;
Text textPrefabText;
void Start() {
textPrefabText = textPrefab.GetComponent<Text>();
textPrefabText.text = "Woohoo! I'm writing text at runtime!";
}
But if you want to modify it in one line of code, you would do this:
void Start() {
textPrefab.GetComponent<Text>().text = "Woohoo! I'm writing text at runtime!";
}
Thank you for your answer. I understand how I can edit the text in the script but how would the player do so dynamically during gameplay?
Well, you're on the right track with the text field. I assume you want the player to enter the text, and have the text update on screen immediately.
So if you have a text input in your scene already, you should notice when you scroll down, a list box called "OnValueChanged".
If you click the '+' symbol, you can attach a script to this, and have the text field call a public function from that script whenever the text input changes.
Write a function that takes the text from the input field, and sets the text on screen to that value. Then attach the script and function to the OnValueChanged list.
When you type into it in play mode, the text on screen will update automatically.
Thank You it helped me update coins text on runtime after watching the ad.
No problem :)
Btw since writing this post I learned that GetComponent() is not a very efficient way of getting a reference as it generates surprising amounts of garbage. I would recommend only using GetComponent() once, caching the value, and then reading from the cached value to save calling that command more than neccesary. Properties are a pretty clean way of doing this. Another approach would also be dependency injection, if you prefer that route.