G’day All,
If I have a number of objects called enemies on the screen, how can I put them into an array?
My initial thought was to do it at the time they were created. I put a declaration in the top of my Game.cs file:
public enemy[] enemiesArray = new enemy[5];
Then when I create the enemies I tried to add them to the array:
for (int i = 0; i < 2; ++i) // This will create 2 sprites
{
Vector2 position = new Vector2((i+1) * 300, (i+1) * 200);
Vector2 direction = new Vector2(10, 10);
float velocity = 10;
int ID = i;
Components.Add(new skull(this, position, direction, velocity, ID));
skullsArray[i] = skull; // This line is wrong
}
I have also tried to to it in the update() method using code like this:
foreach (GameComponent component1 in Components)
{
int index = component1.ID;
if (component1.ToString() == "enemy")
{
enemiesArray[index] = component1
}
}
But that falls down because component1 does not have an ID. I have to assume that as the program enumerates through each GameComponent it can only access a limited range of data for the component.
In the end I want to be able to refer to my enemies as enemy[1], enemy[2], etc.
Thanks,
Andrew.
I don’t see why you cant use a List which works a lot like an array, but it has a variable length. Then you could do this:
You can add enemies just like you would add components (because Components is a
List<GameComponent>Then you can access the enemy:
EDIT: just looked at your code again and I noticed that skull doesn’t exist. Did you mean
Because otherwise you are trying to add a class to the array rather than an instance of the class 🙂