When I pass a derived class object in as a base class object I can’t seem to access the derived class fields. An example may help:
class BaseClass {
// base class fields
string name;
public virtual void SomeMethod(BaseClass obj) { }
}
class DerivedClass : BaseClass {
// Derived class specific fields
float number = 0;
// constructor
public DerivedClass(float num) {
number = num;
}
public override void SomeMethod(BaseClass obj) {
DerivedClass c = obj as DerivedClass;
print(c.number.ToString()); // prints "0", the default value
}
}
class Program {
BaseClass c = new DerivedClass(10);
SomeMethod(c);
}
If I use:
print(obj.GetType());
In “SomeMethod” in “DerivedClass” it does print the correct type (DerivedClass) but the cast causes the object to lose all it’s initialized values. How do I access the values of a DerivedClass object after it has been pass in as a BaseClass object?
EDIT:
To clarify. The different classes are not in the same place so I can’t just call “SomeMethod”, I do need an these instances.
Also, the reason I need use such inheritance is I do not know ahead of time what object the player is aiming at at the time. The player casts a ray and then calls on the objects type by it’s parent type “BaseClass”. It is then up to the subtype class (returned by GetComponent()) to determine how to handle the exact specifics of how to treat the object that was passed in as an argument. The problem is is that the parameter is of BaseClass type but I need the derived class fields that it contains.
Hope this helps explain my confusing situation. Thanks for all replies.