- Home /
Getting the same variable from two different classes?
So let's say I have two classes, Pig and Wall. Pig inherits from Mob, which inherits from PhysicalObject, while Wall directly inherits from PhysicalObject. Now let's say I need to access a common variable from anything that inherits from PhysicalObject, which could be Mass. But I can't just SomeObject.GetComponent().Mass, as that would only work for the Pig class, and I can't say SomeObject.GetComponent().Mass, as I don't think I'll ever even attach that class to a gameObject because it is purely for inheritance purposes. Could I somehow do a check to see if whatever class I'm dealing with inherits from PhysicalObject somewhere down the line?
Answer by Bunny83 · Jul 15, 2018 at 02:56 AM
I think you don't really understand what inheritance means. If Pig and Wall are derived from PhysicalObject they are PhysicalObjects, just more concrete types. You can simply do
float mass = SomeObject.GetComponent<PhysicalObject>().Mass;
This will work even when the actual class is a Pig or Wall instance or anything else derived from PhysicalObject. That's the main purpose of OOP to treat a concrete class in a more general / generic manner.
All I was thinking about was the fact that PhysicalObject wasn't going to be attached to the Pig gameobject, but I didn't realize that Pig class actually IS the PhysicalObject class.
Answer by JVene · Jul 14, 2018 at 02:16 PM
If PhysicalObject owns Mass, you certainly can:
a = SomeObject.Mass;
On Pig and Wall. Since you said that a common variable from PhysicalObject could be Mass, and through Mob Pig gets it just as Wall does.
Since Mass is a member of PhysicalObject, I see no reason for GetComponent, as it's a member of PhysicalObject, not a component on a gameObject, if I follow your description as stated.
Aslong as the $$anonymous$$ass property/field is public then you can access it from any derived class.
I'm sorry for the confusion, Pig and Wall will indeed be attached to gameObjects of the same name. So I'd be trying to get the $$anonymous$$ass variable from an instantiated class such as Pig or Wall.
If $$anonymous$$ass is a member of PhysicalObject, then access is available to Pig and Wall as given.
If you're getting mass (lower case m) from the Rigidbody component of the gameObject that owns the script, then it is still available to both Pig and Wall through gameObject.GetComponent ().mass, since PhysicalObject would have to be derived from $$anonymous$$onoBehaviour, which provides the gameObject member from which to get the component.
But assu$$anonymous$$g I don't know what the class is, just that it inherits from PhysicalObject, how would I access the $$anonymous$$ass variable?
Object$$anonymous$$ass = Object.GetComponent<SomeUnkownClassThatInheritsFromPhysicalObject>().$$anonymous$$ass;