- Home /
[4.6 - UI] Accessing Text in Image inside Canvas via C# Script
Hi all, I'm newbie in Unity 4.6 I use canvas for my UI, and inside the canvas I have an image has text. I want to show the game score that change periodically on that text. How I do that? I mean how I access the text in the image and change it via script? I already read the topic http://answers.unity3d.com/questions/777335/46-ui-changing-the-text-component-via-script.html , but I still can't get the answer, I hope someone can solve this. Many thanks!
Answer by Erisat · Sep 21, 2014 at 11:44 PM
Create a public GameObject variable in one of your scripts, and then drag the gameobject containing the Text component into that variable in the inspector.
public GameObject textgameobject;//set this is inspector or by script, maybe GameObject.Find or something, idk.
void Foo()
{
Text text = textgameobject.GetComponent<Text>(); //get the text component in the gameobject you assigned
text.text = "insert some text here"; //set the text in the text component
}
Thank you for the answer but the text is in image properties, inside the canvas. So, I should put gameobject inside canvas? Ok, I'll try it first
Well I can see that you have a text component. An Image in the new UI is just an image component on a gameobject, so that object isnt an image, its just an object with an image component. Even though they have those new recttransforms, theyre still GameObjects. Do the above, and drag the "ket_JmlPendapatan" object in hierarchy into the inspector variable for the public gameobject textgameobject in the above code. It will then use GetComponent to get the Text component and you can manipulate the text.text string.
SOLVED! Thanks a lot. I missunderstand about image and text before.
Good to hear :) if you want, check out 3dbuzz's tutorial on the new UI. they do a very good job of explaining how everything works. I lost the link, but it's on 3dbuzz.com mainpage. The unity videos are decent, but 3dbuzz explains things in much more detail. Plus, they make me laugh sometimes. $$anonymous$$eeps it interesting.
Answer by arjanstakie · Jun 12, 2017 at 09:52 PM
Hey i've solved the same problem but a little diffrent now (12 juli 2017). Instead of GetComponent< Text>(). I had to use Getcomponent< GUIText>(). The rest is exactly the same as @Erisat's
I think you mean GetComponent< GUIText>(). But even this does not work for me.
are you, "using UnityEngine.UI;" all the way on the top of your script under "using UnityEngine;" & "using System.Collections;" ? I also refer to the text with "public Text something;" ins$$anonymous$$d of using GetComponent<>(), So maybe it is GetComponent < Text>() after all.
Your answer
