- Home /
Changing Two Canvas Text Strings in Code
Hello,
I am most likely being silly here but I cannot seem to change two different strings in code using the new UI system.
At present I want to display the current clip amount as well as the extra ammo they have. How do I do this independently?
This is the code I have for changing one set of text at runtime:
ammoText = Canvas.FindObjectOfType<Text>();
ammoText.text = "Ammo: " + m_Player.CurrentWeaponAmmoCount.Get();
If I do this again (and I know why) it changes both sets of text to the same thing/object. However, I just cannot figure out how to make them separate at the moment...
Answer by David_Biggs · Dec 09, 2014 at 02:24 AM
Text[] texts = Canvas.gameObject.GetComponentsInChildren<Text>();
texts[0].text = "Ammo: " + m_Player.CurrentWeaponAmmoCount.Get();
texts[1].text = "Clip: " + m_Player.CurrentWeaponClipCount.Get();
This will work, although you really should assign the text objects to public variables in your script so you have permanent references to them.
Thanks for the idea about doing it this way.
Just in case anyone else is a silly as I am I did this to get it working:
public Text [] texts;
public Canvas canvas;
void Awake()
{
texts = canvas.gameObject.GetComponentsInChildren <Text> ();
}
void ShowGUI()
{
texts[0].text = "Ammo: " + m_Player.CurrentWeaponAmmoCount.Get();
texts[1].text = "Clip: " + m_Player.CurrentWeaponClipCount.Get();
}
Your answer
Follow this Question
Related Questions
Can't change UI Button Listeners 1 Answer
Move gameobject to button in new 4.6? 0 Answers
Unity 4.6 Beta Controller Menu Button Movement 0 Answers
Unity 4.6 - Rotating with Mouse Issue 0 Answers