Question by
InspectorStrange · Jul 05, 2016 at 12:47 PM ·
listnullreferenceexceptiondynamic
Number of methods based on dynamic list count?
I have a list of classes which I want to call upon, but the list count changes, so I have to make sure I don't reference an index which doesn't exist;
void Update()
{
{
Class class1 = listOfClasses[0];
if (Input.GetButtonDown("Fire1")) { class1.DoClass(); }
}
if (listOFClasses.Count <= 1)
{ return; }
else {
Class class2 = listOfClasses[1];
if (Input.GetButtonDown("Fire2")) { class2.DoClass(); }
}
etc etc
Is there some way I can use the List.Count to create the number of call functions I need, or some other better way, rather than checking the list count at every method call?
Comment
Answer by NoseKills · Jul 06, 2016 at 04:29 PM
Something like this perhaps.
for (int i = 0; i < listOfClasses.Count; i++) {
string fireName = "Fire" + (i + 1);
if (Input.GetButtonDown(fireName)) {
listOfClasses[i].DoClass();
}
}
Your answer
Follow this Question
Related Questions
NullReferenceException : Object reference not set to an instance of an object? 0 Answers
List of Class With GameObject 0 Answers
NullReferenceException: When creating a graph 0 Answers
List remains null after initialisation? 1 Answer
Getting "object reference not set" error when creating a list dictionary. 1 Answer