Can someone give me a basic explanation on what I’m doing wrong here?
I’d like to make a nested class, however I don’t have access to it as I’d expect…
public class SomeClass : MonoBehaviour{
public class parentClass {
public int someInt_A;
public class nestedClass {
public int someInt_B;
}
}
void Start(){
parentClass pClass = new parentClass();
pClass.someInt_A = 1;
pClass.nestedClass.someIntB = 10;
/*
//This Doesn't work either...
parentClass.nestedClass test = pClass.nestClass;
test.someInt_B = 3;
*/
}
}
Line # 15 is my concern, but any suggestions would be helpful…I’m not quite sure what to search via google, so I’m here…sorry for the n00b-like question.
You’ve defined the child class, but not an instance of that class. While you can put class definitions inside each other, it’s usually more useful and less confusing (especially while you’re getting used to the concepts) to have each class definition on the root level, or at least at the same level as each other. That way, you won’t be tempted to think that defining the class also creates an instance of the class, as you’ve done here. (Putting class definitions inside each other has its uses, but mostly just for the sake of limiting scope and preventing collisions between similarly-named classes used in different contexts; one example in Unity is ParticleSystem.Particle, which was defined within ParticleSystem so that it wouldn’t collide with the legacy Particle class.)
You’ll also be better served by getting into the habit of using common coding conventions, which will make it easier to keep straight in your head which things are classes and which things are instances. In this case, using CapitalNames for classes and camelCaseNames for instances/variables (which is consistent with most of Unity’s codebase, e.g. GameObject vs gameObject) will make it easier to follow.
public class SomeClass : MonoBehaviour{
public class ParentClass {
public int someInt_A;
public NestedClass nestedClass = new NestedClass();
}
public class NestedClass {
public int someInt_B;
}
void Start(){
ParentClass pClass = new ParentClass();
pClass.someInt_A = 1;
pClass.nestedClass.someInt_B = 10;
}
}
Ah, copy that…
I was thinking since I’ve defined “pClass” (child class), classes nested within would inherent from that definition…(sorry for most likely incorrect terminology). Either way, I’m clearly wrong.
Thanks a bunch! I’ll take this and work from it, also thanks for the link! I’ve reviewed that as well…