- Home /
Unity 4.6 Change the content from a text Object through script
Hi, I have got the problem that I want to change a text GUI element through script in unity 4.6 for showing a score in my game but I do not get it to work because I dont know how to access the Text component. So if anyone could help me I would be rally happy :-)
P.S.: I'm sorry for my bad english
Answer by Landern · Aug 28, 2014 at 02:33 PM
You get it like anything else.
// UnityScript
import UnityEngine.UI;
var someText: Text;
function Start()
{
someText = GetComponent.<Text>(); //
}
function Update()
{
someText.text = "Hello and junk";
}
// c#
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class SomeScriptName : MonoBehaviour
{
public Text someText;
void Start()
{
someText = GetComponent<Text>();
}
void Update()
{
someText.text = "Hello im some text";
}
}
Ohh I see.
import UnityEngine.UI;
that is what i have forgotten. Thanks a lot :-)
That's not gonna be efficient if the user has more than 1 text element in their canvas. It will end up changing all of them. Best thing to do is to do the following, it's hardcoded so :)
void Start()
{
GameObject canvas = GameObject.Find("Canvas");
Text[] textValue = canvas.GetComponentsInChildren<Text>();
textValue[enter the index of the text object here].text = "hey";
}
i would love to find out another way, this seems too sloppy.
@Ace_Flooder, it would not change all of them, it would get the first Component of type Text.
If you want to keep references to a multitude of objects, setup a Dictionary of type string and of type Text. Use the key by name to reference the reference value of the Text type and make your modifications to the text property as needed.
In the case you posted you would have to know the index by int. that would be sloppy, at least using a $$anonymous$$ey Value Pair type, you can associate logical key names with the object.
textValue[18] would require a look up for the programmer to remember what it is.
using the dictionary method, you would use something like
textValue["scoretext"].text = scoreInt.ToString();
In the case above they were asking about a single component, you are conflating the issue.
Answer by Blyler · Mar 09, 2015 at 07:34 AM
I wrote the following function, based on @Ace_Flooders excellent answer, for finding text elements by name using Linq:
private Text GetTextObjectByName(string name)
{
var canvas = GameObject.Find("Canvas");
var texts = canvas.GetComponentsInChildren<Text>();
return texts.FirstOrDefault(textObject => textObject.name == name);
}