This time I have problem with virtual fields.
I have core class for my game objects. This class contains a field with Model class object. Model’s object contains values such as position etc.
Now – while drawing I need to read position of each object from it’s model. The problem starts when instead of default model class I’m using derived. Example:
abstract class GenericGameObject { public DefaultGameObjectModel Model = new DefaultGameObjectModel(); } class Missile : GenericGameObject { public new MissileModel Model = new MissileModel(); } class DefaultGameObjectModel { public Vector2 Position = new Vector2(){X=0}; } class MissileModel : DefaultGameObjectModel { } Missile m = new Missile(); m.Model.Position.X = 10; // NOT OK! ((GenericGameObject)m).Model.Position.X == 0
I tried to make Model defined as virtual property instead of field, but this fails because derived properties have to be of same type as their base. Casting is futile because there will be many other model types. What can I do if I want to read a value from derived class, not from base?
I asked this question already but the answer didn’t brought any solution. Explaination:
-
to use interface IGameObjectModel
Concept is good, but I have to enforce fields. Interfaces can’t define fields so I have to define property. But then I can’t do IGameObjectModel.Position.X=10 because Position is not a field.
-
to make GenericGameObject a generic type such as GenericGameObject and Missile a type derived from GenericGameObject I couldn’t then cast a missile to GenericGameObject and generally store those object on same list. Of course I could make main base type which those two could inherit from, but then I wouldn’t have access to Model field.
-
to make model a property instead of field. It is impossible to change property type in derived class.
Whad can I do?
In this case your best approach would be to assign the value of your parent field to be an instance of your derived class, then either cast it back to your derived class or hold on to a reference of your derived class (probably better).
Or you could go down this road, which I like the best…
This solution gives you access to your base model instance from the context of the base class, while giving you access to your concrete model instance from the inherited class.