- Home /
How to access variables inside a loop in C#?
I used to program games in flash (AS3), and there I was used to do it this way.
var btn0, btn1, btn2: Object;
for(var i:uint = 0; i< 3; i++)
{
this["btn"+i].visible = true;
}
There's a way to do it in Unity with C#?
No, you'd get a compiler error when you tried to define 3 variables with the same name.
Answer by Tehnique · Mar 17, 2015 at 05:05 PM
Yes, just put your button references in an array, iterate it, and use "SetActive" to turn them on or off. But, remember that you can only reactivate (show) the buttons if you still have them referenced. Inactive objects cannot be found using "Find" or "GetComponent".
Thanks, I'll do that and thanks for the tip about inactive objects as well.
Answer by boysenberry · Mar 17, 2015 at 09:04 PM
I think this would do what you're looking for:
GameObject btn0, btn1, btn2; GameObject [] buttons = {btn0,btn1,btn2}; for (int i = 0; i < buttons.Length; i++) { GameObject myBtn = buttons[i]; }
Upon further thought, you might be talking about reflection.
If so then its more like this:
using System.Reflection;
Type objectType = this.GetType (); // can be any object
// for object fields
FieldInfo theField = objectType.GetField ("someField"); Debug.Log (theField.GetValue ());
// for object methods
MethodInfo theMethod = objectType.GetMethod ("someMethod"); theMethod.Invoke (this); // can add parameters as well
more info here:
https://msdn.microsoft.com/en-us/library/system.reflection(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/4ek9c21e(v=vs.110).aspx
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Renderer on object disabled after level reload 1 Answer