- Home /
How to refer to object based on value of a variable
Hi everyone,
I have a range of game objects which I'm wanting to make changes to based on the value of another variable. The objects are of type TextMeshProUGUI, if that is relevant.
So e.g. suppose I have two objects called Text1 and Text2. If the variable == 1, I want Text1 to be "hello"; if the variable == 2, I want Text 2 to be "hello". I appreciate I could just write this out manually fairly simply, but I want to avoid that for various reasons (there are many objects I need to change + I need flexibility).
The following code doesn't work:
If (randomvariable == N)
{TextN.text = "hello"};
After several hours googling, I'm no further forward, other than gathering it's the result of C# being statically typed. I've seen people suggesting using dictionaries, e.g. the following:
static Dictionary<int, string> myDict = new Dictionary<int, string>();
myDict.Add(1, Text1);
and then within a method
myDict[1].text = "hello";
But it doesn't work. I've also seen people suggesting using arrays - but I don't see how that would help. Sure, I can store the names in an array, but how would I then treat it as a class name to which I can refer?! As you can probably tell, I'm a beginner, so any advice on how to solve it, or where to look, would be much appreciated!!!
Many thanks
John
Could you please share the entire script? In the parts you shared, I cannot find a problem so it might be somewhere else.
Answer by Kofiro · Nov 24, 2020 at 07:54 PM
Hello, are the objects Text1 and Text2 gameobjects with text components?
Could you also share more bits of your code so I see where you have your issues.