Search code examples
c#monogame

updating all list items


Note that I'm fairly new to programming.

So I made a list for all the children sprites of the parent sprite in my game (children) and I made another list (childrenSpeed) that stores each of the millisecondsPerFrame float value from the children sprites, also attached to the parent sprite.

The problem is: if I need to update the millisecondsPerFrame value for (as an example) the playerHead, then I need to type:

playerHead.millisecondsPerFrame = (value);

but I want to make it so that I can use one line of code to update all the values in the childrenSpeed list for all the children.

I tried to use a

player.childrenSpeed.ForEach(...)

for this but I couldn't seem to let it work.

This is my LoadContent method: (the last float in the playermovement is the millisecondsPerFrame value)

protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(Game.GraphicsDevice);

    // Player sprite
    player = new PlayerMovement(Game.Content.Load<Texture2D>(@"Images/" + s1[0]), new Vector2(150, 150), new Point(20, 35), 0, new Point(0, 0), new Point(1, 11), 1.5f, 1.75f, 65f);
    playerHead = new PlayerMovement(Game.Content.Load<Texture2D>(@"Images/" + s1[2]), new Vector2(150, 150), new Point(20, 35), 0, new Point(0, 0), new Point(1, 11), 1.5f, 1.75f, 65f);
    // playerHead is stored in the children list attached to player
    player.children.Add(playerHead);
    // the millisecondsPerFrame value from playerHead is stored in the childrenSpeed list attached to player
    player.childrenSpeed.Add(playerHead.millisecondsPerFrame);

    // Base loadcontent method
    base.LoadContent();
}

And this is my Update method:

public override void Update(GameTime gameTime)
{

    if (player.running == true)
    {
        Console.WriteLine("Lopen");
        player.millisecondsPerFrame = 30;
        // I need my childrenSpeed code for millisecondsPerFrame here
    }

    else if (player.running == false)
    {
        Console.WriteLine("gestopt");
        player.millisecondsPerFrame = 65;
        // I need my childrenSpeed code for millisecondsPerFrame here
    }

    if (player.walking == false)
    {
        // not done yet
    }

    player.Update(gameTime, Game.Window.ClientBounds);
    player.children.ForEach(c => c.Update(gameTime, Game.Window.ClientBounds));
    base.Update(gameTime);
}

So I need something like this:

public override void Update() 
{
    if (player.bool == ...)
    {   
        player.milliSecondsPerFrame = (value);
        // Each element in the player.childrenSpeed list = (value) (same as player)
    }
}

Solution

  • It worked by using a foreach loop in the Update method:

    foreach (Sprite children in player.children) // player.children is the sprite list
    {
        children.millisecondsPerFrame = value; // I assign the millisecondsPerFrame float value
    }
    

    But thank you for the answers.