Dynamic function

Good afternoon,

I’m looking for a solution to call a function depending on a variable:

For example:

I have 3000 lists: list1, list2, list3…list3000

How can I get one list of them having the name of one of the lists? for example, destroy it:

string varName = “list” + “2”;
Destroy(list + varName) // it have to destroy list2

Thanks a lot

The Destroy() function is for GameObjects. Could you please elaborate a bit more on what you are planning to do?

Store them in another list or array:

List<type>[] Lists;
List<int,List<type>> Lists;
Dictionary<string,List<type>> Lists;

You can not destroy lists as they are no GameObjects, so I assume this is an example. But simply store your variables in a container like shown above and you can access them by an id.

GameObject[] Objects;
for(var i=0; i<Objects.Length;i++){
Destroy(Objects[i]);
}
1 Like

Destroy function only was an example.

I´m going to try to explain better with other example:

If I have 3 int variables: a = 0 ; b = 4; c = 1.

Suppose I have the string varibale myString = “a”.

How can I call variable a only taking myString value.

Thank a lot!

Through reflection.

But that’s really, really slow and brittle and not a good idea. It’s also hard!

99% of the time the better solution is to not do that.

1 Like

Why you not just call the variable? MyClass.myString?
Reflection is slow and you only should use it in editor tools or initialization methods if ther eis no other way to solve your issue.

Maybe you work on such a script, otherwise you should consider to store them not as a variable but in a container as I showed you:
Dictionary<string, string> MyStrings;
//Set Value:
MyStrings.Add(“mystring”,“valueOfMyString”);
//Get Value:
Debug.Log(MyStrings[“mystring”]);

1 Like