Is it possible to use . Operator to access variables in classes in lists
I've been trying to find an answer to this question but can't seem to find one, or I don't know how to ask google in a way to have it tell me.
I want, essentially, a file branch structure for classes. Classes with lists of classes with lists of classes.
Is it possible to do something like:
Class1.ListofClasses1.ListofClasses2.variable
I can think of several things that might mean. Of course, you can make things that use 3+ dots in a row, but no one would call that a List of classes. And a List would generally use [i], anyway.
It might help if you focused on what you want to accomplish?
Answer by Eno-Khaon · Mar 24, 2016 at 09:44 AM
The short answer is yes, the long answer is the inspector may hate you for it.
// C#
// inside Class1
List<Class2> class2List = new List<Class2>();
// ...
// Populate the list as desired
// ...
class2List[element].class3List = new List<Class3>();
class2List[element].class3List[element2] = new Class3();
// ...
class2List[element1].class3List[element2].intVariable = 7;
Everything there is perfectly normal, if a bit long-winded once you have a long enough chain.
Now, you might be wondering at this point... Why would the inspector hate you? Well, here's an example of what NOT to do:
Create two classes, each of which contain a list of each other's class. Serialize both classes so you can view their contents in the inspector... Now the inspector can find itself in an infinite loop. Class1 includes a list of Class2, which includes a list of Class1 which, well, continues forever and locks up Unity.
The references will simply be references in this case, so as long as they're not viewable in the editor, there's nothing unusual about their behavior.
That said, it certainly lets you have fun with things:
// Inside ClassA
List<ClassB> B = new List<ClassB>();
B[0] = new ClassB;
B[0].A = new List<ClassA>();
B[0].A[0] = this;
B[0].A[0].B[0].A[0].B[0].A[0].B[0].A[0].B[0].intVariable = 7;
Your answer
Follow this Question
Related Questions
Removing item from list makes it appear at the bottom ? 1 Answer
Finding the max Y position value in a list of game objects and assigning it to a variable? 0 Answers
Nested class Lists inspector overlapping bug 1 Answer
All crops in list growing at once when they are supposed to grow individually 0 Answers
Only spawning power ups that the player wants in that game 1 Answer