Reputation:
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 Plane : GenericGameObject { public void shoot(Missile m){ m.Model.Position.X = 10; } }
class Missile : GenericGameObject { public new MissileModel Model = new MissileModel(); }
class DefaultGameObjectModel { public Vector2 Position = new Vector2(){X=0}; }
class MissileModel : DefaultGameObjectModel { }
Plane p = new Plane();
Missile m = new Missile();
p.shoot(m);
// 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?
Upvotes: 0
Views: 2446
Reputation: 245499
You could also create an IGameObjectModel interface and then implement it in each of your Object Model classes. Your GameObject would then have an instance of IGameObjectModel.
Upvotes: 1
Reputation: 1503869
It sounds like your GenericGameObject
needs to be a generic type, where the type parameter derives from DefaultGameObjectModel
:
abstract class GenericGameObject<TModel>
where TModel : DefaultGameObjectModel
{
private TModel model;
// Or whatever
public TModel Model
{
get { return model; }
protected set { model = value; }
}
}
Upvotes: 3