c# - Entity management, with inheritance method calls -


so, creating game entity system.

public class bullet : entity

public class npc : entity

public class tank : entity

public class entity

a entity has functions: update(), render()

i created list so:

list<entity> entities = new list<entity>(); 

and cycle through of them , call update() / render()

but stored bullets or npcs not called update or render functions.

tl;dr

how store different classes update/render function , call in loop of them.

entity

class entity {     public void update(gametime gametime, graphicsdevice gd, player p, tilemap tm, entitymanager em)     {      }     public void draw(spritebatch sb)     {      } } 

bullet

class bullet : entity {     public new void update(gametime gametime, graphicsdevice gd, player p, tilemap tm, entitymanager em)     {     }      public new void render(spritebatch spritebatch)     {     }  } 

entity manager

class entitymanager {     public list<entity> entitylist = new list<entity>();      public void update(gametime gametime, graphicsdevice graphics, player p, tilemap tm, entitymanager em)     {         int = 0;         while (i < entitylist.count)         {             entitylist[i].update(gametime, graphics, p, tm, em);             i++;         }     }     public void render(spritebatch sb)     {         foreach (bullet entity in entitylist)         {             entity.draw(sb);         }     } 

}

change entity's methods use virtual keyword:

public virtual void update(...  public virtual void draw(... 

and in child classes, want override base class' methods using override keyword, not new keyword:

public override void update(...  public override void draw(... 

by using virtual/override combo in inheritance tree, enabling polymorphism, allow child classes' methods invoked, when doing list<entity>.

link more info on polymorphism in c#.


Comments