Search code examples
c#xnaabstracttypeofderived

process functions and variables from derived class of abstract


How do i circumvent questioning from any derived class and writing the code twice?

I have tried the following:

Type t = GetType(obj); 
(obj as t).health

By doing this, Visual Sudio saysme health is not member of... blah

Here's my code:

// gameobjects-class    
abstract gameobject
{
Vector2 Position
void update()
etc...


class meteor : gameobject
{
float rotation
etc...

class player : gameobject
{
int health, attackpower
etc...

class enemy: gameobject
{
int health, attackpower
etc...

External class accessing data from GameObject

class anyclass
{
void checkhealth(gameobject obj)   // QUESTION:
{
if (obj as player).health = 0      // 
     kill(obj)                     // 
if (obj as enemy).health = 0       // 
     kill(obj)                     // 

Any suggestion? Thanks!


Solution

  • You can create an interface for living objects and then pass that to the method

    interface ILivingGameObject
    {
        int Health {get;set;}
    }
    
    class Player : GameObject, ILivingGameObject
    {
    }
    
    void CheckHealth(ILivingGameObject obj)
    {
         if(obj.Health == 0)
              kill(obj);
    }
    

    You can read more on Interfaces here


    Alternatively you can create a LivingObject class that both player and enemy inherit from and pass this to the method

    class LivingObject : GameObject
    {
        int Health {get;set;}
    }
    
    class Player : LivingObject
    {
    }
    
    void CheckHealth(LivingObject obj)
    {
    }