[C#] Is it possible to add Sprites to Lists?
Asked Answered
F

5

0

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 🙂

Firmament answered 3/1, 2024 at 17:6 Comment(0)
M
0

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

(excuse my english)

Murdoch answered 4/1, 2024 at 11:22 Comment(0)
C
1

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);
    }
}
Charissecharita answered 4/1, 2024 at 12:41 Comment(0)
F
0

Murdoch Indeed, there should be, thank you!!

Firmament answered 4/1, 2024 at 17:15 Comment(0)
F
0

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?

Firmament answered 4/1, 2024 at 17:21 Comment(0)
C
0

Firmament 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).

Charissecharita answered 5/1, 2024 at 9:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.