Sam
Sam

Reputation: 2347

Creating infinitely spawning enemies

Since this is just my second game, I'm still a little unsure of how to continually create and use new instances of objects. I know in actionscript that there is a way to create a new instance of something without giving it a name and then loop through a list of some kind. But I'm wondering what would be the best way to do this in c# using xna. If anyone could provide a simple code example it would be appreciated.

Thanks

Upvotes: 1

Views: 2472

Answers (4)

Dave Bish
Dave Bish

Reputation: 19656

Using the http://en.wikipedia.org/wiki/Flyweight_pattern is a good start, as it will conserve resources.

Upvotes: 0

Martin
Martin

Reputation: 40365

Are you looking for something like the below:

// A sample enemy class
class Enemy
{
    public int EnemyStrength { get; set; }

    public Enemy(int strength)
    {
        EnemyStrength = strength;
    }
}

class Program
{
    static void Main(string[] args)
    {
        // A List to hold all the enemies
        List<Enemy> Enemies = new List<Enemy>();

        // Create some enemies
        for (int i = 0; i < 5; i++)
        {
            Enemies.Add(new Enemy(i));
        }

        // Display the strength of them all.
        foreach (Enemy enemy in Enemies)
        {
            Console.WriteLine(enemy.EnemyStrength);
        }

    }
}

The important bit is Enemies.Add(new Enemy(i)) which instantiates and adds an enemy to the list without assigning it to a named variable - which I think is what you are asking.

Upvotes: 2

ahmet
ahmet

Reputation: 646

XNA provides an infinite game loop by invoking Update and Draw continually. As Chris said, keep your objects in a list and each time you need to add a new object, instantiate it in Update method. Then let Update and Draw methods to traverse the list and call each object's Update and Draw methods respectively.

Upvotes: 0

Chris
Chris

Reputation: 27627

I don't know about XNA specifically but there are a lot of collections in C# that could be used. Most interesting are the generic ones like List<MyObject> which provides a strongly typed list (ie no casting needed). Other options would be things like Arrays, Dictionaries (if you wanted to give them some names but also wanted to be able to easily loop through them or if you need to be able to find a single instance by some key quickly).

There are a lot of others as well but these are some of the most common ones.

Sample code (assumes you have a class called enemy):

List<Enemy> myList = new List<Enemy>();
for (int i = 0; i < 100; i++)
{
        myList.Add(new Enemy());
}

Obviously this doesn't produce infinite enemies but it shows how to add a bunch of new unnamed objects to a simple list.

You might use it something like this:

foreach (Enemy badguy in myList)
{
    badguy.Update();
}

Upvotes: 1

Related Questions