Croccy
Croccy

Reputation: 21

Making an instantiated class array with a method

I have a class "Bullet" which I instantiate using a method CreateBullet(), since there are going to be multiple bullets i decided that I should make bullet an array, though this didn't work out and I've spent an hour on trying to fix it.

What I call in my Initialize method:

Bullet bullet[] = Bullet.CreateBullet[1]();

The Bullet class:

class Bullet
{
    public float2 position;
    public float angle { get; set; }
    public float speed { get; set; }
    public static Bullet CreateBullet()
    {
        Bullet bullet = new Bullet()
        {
            position = new float2()
        };
        return bullet;
    }
    public void Move()
    { 
    }
}

Could you please show me what's wrong with the code? Thank you in advance.

Upvotes: 0

Views: 46

Answers (2)

TheGeneral
TheGeneral

Reputation: 81483

You could do something like this, not quite what you where trying to achieve, but it might inspire you a bit more

Usage

// Create your bullets
var bullets = new List<Bullet>();

// Create a raw/empty bullet with default properties 
var newBullet1 = new Bullet();

// Create bullet with some initialized properties
var newBullet2 = new Bullet()
   {
      Angle = 35, 
      Position = 0, 
      Speed = 200
   };

bullets.Add(newBullet1);
bullets.Add(newBullet2);

Something extra for fun

// Move all your bullets at once
foreach (var bullet in bullets)
{
   bullet.Move();
}

Upvotes: 0

John
John

Reputation: 3702

With this, you create an array of 5 bullets:

        Bullet[] bullets = new Bullet[5];

And then you need to fill the array by creating a bullet for each array entry:

        for (int i = 0; i < bullets.Length; i++)
        {
            bullets[i] = Bullet.CreateBullet(); 
        }

You can wrap this logic in a function:

    public Bullet[] CreateBullets(int amount)
    {
        Bullet[] bullets = new Bullet[amount];
        for (int i = 0; i < bullets.Length; i++)
        {
            bullets[i] = Bullet.CreateBullet(); 
        }

        return bullets;
    }

And then you can use a function to initialize the array:

    public void Test()
    {
        Bullet[] bullets = CreateBullets(5);
    }

Upvotes: 2

Related Questions