Using a button to change the text of a text object
1. Insert a Text object using Create -> UI -> Text
2. Insert a Button, using Create -> UI -> Button
3. Create a new script, using Create -> C# Script
4. At the top of the script, add another using statement,
using UnityEngine.UI;
at the top class, after the first { add the following code.
Text message;
This creates a Text object called message
5. In the Start method, add this,
message = GetComponent<Text>();
this finds the first Text component and assignes it the message variable.
6. Create a new public method called DoSomething, like this.
public void DoSomething() { message.text = "Hello World"; }
7. Save the script and return to unity
8. Attached this script to the Text object in UnityEngine
9. Select the Button object
10. Click the + in the On Click() box.
11. Drag the Text object (where the script is attached) onto the box that currently says None (Object)
12. In the drop down box that currently shows No Funtion, select YouScriptName, then the method name.
You should note that the icon for the text object you dragged down should have changed from a box to a C# logo.
13. Now run your app. when you click the button, the text should changed.
Leave a Reply