- Home /
How to change Toggle Text using C#?
Hi Guys,
Can someone please explain to me how I can change the display Text/Label of a Toggle from within C# code?
I'm new to Unity but have many years of C# experience.
Thanks in advance!
Answer by Suddoha · Oct 02, 2015 at 02:19 AM
You could have a public variable of type Text (which belongs to the UnityEngine.UI namespace) in your script. The object that you attach this script to will then show a slot in the inspector. You can drag&drop any gameobject onto that slot that has a Text component or use code to find the appropriate text component if you don't like to assign it there.
In the script, you can then simply use something like
toggleText.text = "some text";
You could also have the variable of type Toggle, GameObject, Transform but then you'd have to find the text component in the components or children first, depending on the hierarchy.
Answer by devsolo · Oct 02, 2015 at 07:20 AM
Hi Suddoha,
I don't really want to do anything at design time, I would prefer finding the Toggle and then changing the Text at runtime using code, as a future requirement will be to create N number of Toggles based on an external data source and access these dynamically within code.
I already have the code defined, which finds the Toggle and can access the child components. But there doesn't seem to be a Text component or property to work against.
Currently from what I can see, the hierarchy within the Toggle is: Toggle - Background - Label
These are the only child components I can see, the Toggle has 2 children, Background and Label. Label is actually just a RectTransform. And Label doesn't have any children. So I'm not sure how to change the text?
Well, then just use GetComponent<Text>
on the Label's gameobject, or if you're sure that there's only one text component, you can also use GetComponentInChildren<Text>()
. They both have a plural version too GetComponents<...>
and GetComponentsInChildren<...>
respectively, but then you'll (of course) get an array of these components.
You can do that with every component that is attached to gameObjects. :)
Your answer
Follow this Question
Related Questions
How Do I Turn Off Toggle in a ToggleGroup ? 1 Answer
how do i toggle image effects on my camera with a script 1 Answer
Toggle script with button 0 Answers
Accessing Variables from another object Script 1 Answer
Flip over car after tips over? 1 Answer