Search code examples
xnaspritecollisionmonogame

How do I delete a GameComponent from Game.Components?


Basically my game is to stop the rocks falling from the sky using a plank. I'm not sure what is not functioning correctly, but here is my code: In the RockManager class

public void CheckForPlankCollision(Plank plank)
{
    foreach (GameComponent component in Game.Components)
    {
        if (component is FallingRock rock)
        {
            if (plank.Bounds.Intersects(rock.Bounds))
            {
                rock.HandleCollision();
                Rectangle bounds = rock.Bounds;
            }
        }
    }
}

In the Rocks class

public void HandleCollision()
{
    //rockPosition = rockAfterImpactPosition; // I tried to move it offscreen
    //rockPosition = Vector2.Zero; //I tried for any reaction
    //this.Enabled = false; // tried this
    //Game.Components.Remove(this); //tried this
}

I'm also trying to implement a scoring system. (add 1 point if the rock hits the plank, subtract a point if it hits the ground)


Solution

  • Try casting this as an IGameComponent or GameComponent object.

    public void HandleCollision()
    {
        Game.Components.Remove((GameComponent)this);
    }
    

    Tell me if this works for you !

    EDIT: You might also want to defer the deletion of your game object to later, when it isn't used by the foreach (GameComponent component in Game.Components) loop, which might have a lock on removing elements during that time.