Sorry if I have missed an answer elsewhere, I may just not know for what to search. Is it possible to access a variable name similarly to how an integer can be added to the end of a string? I.e., access variable1, variable2, … with variable+i for i incrementing?
Thank you for any explanations or links to an answer! Also, I don’t have much experience with C#, so if it’s feasible with Javascript, that would be prefered.
It is possible.
You could use Reflection to get all class PropertyInfo and FieldInfo that follow your specific pattern then iterate over them setting their values but Reflection is very expensive and this process would affect drastically the performance of your game.
I can propose you two different solutions. First one is to change your variables for an array (or list) of variables then iterate over the array, but, you feel that doing that will be a lot of work you can simply create an local array containing your variables and then iterate over this local array.
Solution 1:
// suppose you have these variables
var item1:MyClass;
var item2:MyClass;
var item3:MyClass;
// (...)
var itemN:MyClass;
// you can change it for:
var items:MyClass[];
// or
var items:List.<MyClass>();
// and instead of accessing them directly
// item1.myProp
// you would acces them using an index
// item[1].myProp
Solution 2:
// suppose you have these variables
var item1:MyClass;
var item2:MyClass;
var item3:MyClass;
// (...)
var itemN:MyClass;
// you can make a list containing all of them
var items:List.<MyClass>;
items.Add(item1);
items.Add(item2);
items.Add(item3);
// (..)
items.Add(itemN);
// and acces the variables just like the first method
Both solutions will work fine with classes but be careful about the second solution because it WONT WORK WITH STRUCTS. This means that it wont work with Vector3, Vector2, float, int, double, short, and any other type derived from ValueType.