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!
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!
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.
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
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?