Hay all: (A repost from UI forums… Posted here as well seeing it has more to do with Scripting)
I am just learning the new UI system, not that I knew the old one As a beginner, I have searched the forums and some sites for information of how to change the a TEXT element of a UI via C# Script.
Basically what I have done is created a Keypad with buttons that pass a variable to the script as a string. the script adds the new input to the old, So click 1 and 1 is sent, click 2 and 2 is added to 1 as a string, so 12, this works fine, however the question is, how do I update the a UI text element with the new string.
Key Pad to Script, script to Text element.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class test : MonoBehaviour {
public string MyText;
public void MyFunction (string MyCount)
{
if (MyCount == "CANCELED")
{
print("Canceled");
MyText="";
MyCount="";
}
MyText += MyCount;
print(MyText);
}
}
I would like the string to be displayed by the UI.Text…??
I managed to get the UI Text to change via script, but I am left thinking there are better ways of achieving this so I though to post the updated script and leave the door open to suggestions and examples that will make this more efficient, I am some what reluctant on putting things in Update unless they absolutely need to be, so the question remains, Must it be?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class test : MonoBehaviour
{
public string MyText;
public GameObject Kp_Display;
public void MyFunction (string MyCount)
{
if (MyCount == "CANCELED")
{
print("Canceled");
MyText="";
MyCount="";
}
MyText += MyCount;
print(MyText);
}
void Update ()
{
Text text = Kp_Display.GetComponent<Text> ();
text.text = MyText;
}
}
Thanks for any suggestions or examples that will make this simple code more simple, thanks.
You probably don’t have to set the text every update. But I honestly don’t know what the performance impact would be whether having a condition check to check every update, or just letting the text field update every update.
You could try something like this sudo-code and see if it saves any performance. You might have to make another variable called PreviousCount or something like that, then do:
if(MyCount != PreviousCount) {
update text here;
}
That way you can first see if the count changed at all from the previous update. If it did, update the text field. If not, leave it alone. Not sure if it will have any meaningful impact on performance.
That is what I was looking for, Warping it all up in one function!. (SOLVED).
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class UI_Control : MonoBehaviour
{
public string MyText;
public GameObject Kp_Display;
private Text text;
public void MyFunction (string MyCount)
{
Text text = Kp_Display.GetComponent<Text> ();
if (MyCount == "X")
{
MyText="";
MyCount="";
}
MyText += MyCount;
text.text = MyText;
}
}