I don’t even know what I want to ask or how to ask it properly. So here’s an example pseudocode:
class UpperClass {
int myLevel = 50;
LowerClass lowerClass;
}
class LowerClass : MonoBehaviour {
void ReadMyLevel() {
Debug.Log(_up_.myLevel);
}
}
I feel kind of tired putting 50 references to the same variable. I was wondering whether I could reference a script that this script is contained in? I wonder if I can (without setting reference) access UpperClass.myLevel
from LowerClass.ReadMyLevel();
class LowerClass : MonoBehaviour {
int myLevel; // could solve it, but gets annoying 50 entires in
void ReadMyLevel() {
Debug.Log(_up_.myLevel);
}
}
Short answer is no. Consider in this case, what if your LowerClass is referenced by two UpperClass’s? This is absolutely possible and what answer could that line give?
You can store a reference to the UpperClass from the LowerClass and assign this reference when you assign it the other way. Unity’s Transforms do something like this with their parents, which is why root transforms can access all of their children and the children can all do transform.parent. (In this case, the answer to the above question is that the child enforces only having one parent; if you assign it to another parent, it removes itself from the first parent before attaching to the new one.)
Notice that LowerClass isn’t actually “inside” UpperClass; UpperClass just has a reference to LowerClass. It’s possible that 50 different copies of UpperClass all refer to the same copy of LowerClass, or that zero do.
If you want LowerClass to access data in UpperClass, you need to give LowerClass a reference to the specific copy of UpperClass that it’s supposed to look at. (That is, create a variable of type UpperClass inside of LowerClass, and set that variable to an appropriate value.)
1 Like
Well seeing that UpperClass isn’t a MonoBehaviour, is there only a single instance of UpperClass in your game? If so you could consider doing the usual singleton thing where you create a static reference to the only instance of UpperClass. Or even just make everything static in UpperClass. If there are multiple instances of UpperClass then you’ll just have to tell LowerClass which reference to use though.
1 Like