Question

In my XNA game, I have a foreach loop that runs from a list of sprites (SpriteList). This list is a mixture of its child classes.

In my update method I'm using:

foreach (Sprites s in SpriteList)
{
    s.Update();
}

This is calling the update method of the Sprites class (which is abstract), but I want it to use the update method of the child classes that it is made of.

I have tried making the update method of the Sprites class abstract and virtual, and both have been creating errors when I call the methods

EDIT:

My sprites class is:

public abstract class Sprites
{
    public Texture2D SpriteTexture;
    public Rectangle SpriteRectangle;
    public SpriteTypes SpriteType;
    public Color SpriteColour;
    public bool SpriteAlive = false;

    public Sprites(Texture2D TextureIn, Rectangle RectangleIn)
    {
        SpriteTexture = TextureIn;
        SpriteRectangle = RectangleIn;
        SpriteType = SpriteTypes.Sprite;
        SpriteColour = Color.White;
    }

    public void Update()
    {
        // This is what's being called, rather than the update methods of the child classes
    }
Was it helpful?

Solution

You need to make the method virtual in the Sprites class (or abstract if there is no implementation in that class) and use the override keyword when you declare the method in each of the child classes.

OTHER TIPS

This is what you need:

public abstract class Sprites
{
    public Texture2D SpriteTexture;
    public Rectangle SpriteRectangle;
    public SpriteTypes SpriteType;
    public Color SpriteColour;
    public bool SpriteAlive = false;

    public Sprites(Texture2D TextureIn, Rectangle RectangleIn)
    {
        SpriteTexture = TextureIn;
        SpriteRectangle = RectangleIn;
        SpriteType = SpriteTypes.Sprite;
        SpriteColour = Color.White;
    }

    // note the `abstract` keyword here,
    // which means "this method is to be implemented in child classes" 
    public abstract void Update();    
}

public class ChildSprites : Sprites
{
     public override void Update()//note `override` keyword
     {
         // ...
     }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top