HI Everyone,

I'm trying to add a Sprite2D node to a C# list. The code below shows now errors and builds, but the loop dies on the first iteration:

var coinSprites = GetNode<Node2D>("CoinSprites");
List<Sprite2D> coins = new List<Sprite2D> { };
		
foreach (Sprite2D coin in coinSprites.GetChildren())
{
    coins.Add(coin);
}

Any ideas welcome!
And, if this really just a bad idea in general, and there's a better way to move some sprites into an array or list, please let me know 🙂

should there round brackets at the end?
...List<Sprite2D> coins = new List<Sprite2D>();

(excuse my english)

  • d13 replied to this.

    GetChildren returns a Node, you likely want to cast it to a sprite safely.

    foreach(Node child in GetChildren())
    {
        if (child is Sprite2D sprite)
        {
            coins.Add(sprite);
        }
    }
    • d13 likes this.

    Thanks for the above, those fixed my problem 🙂

    What I'm trying to do is move the sprites into some kind of array so that's easier for me to manipulate them for another tasks, where I'll be adding and removing them from this array. In your opinions, does it make sense to use a C# List for something like this, or is there a better way?

      d13 sure, that seems fine. I can think of a project where I do something similar, keeping references to enemies in a list as it's simpler to process the data rather than deal directly with nodes (faster too, in my project).