Search code examples
c#xnamonogame

XNA Framework / Monogame, creating 100 instances of object


I am new to MonoGame and C#, and I want to initialise e.g. 100 instances of 1 object (Wheel). I have thought about using a for-loop, but I don't know how to go further and actually make those 100 instances.

Do I have to make an array of objects? Or can I just create e.g. Wheel1 wheel = new Wheel();?

This is the code I have already:

protected override void Initialize()
    {
        // TODO: Add your initialization logic here
        _wheel = new Wheel();
        _wheel.Position = new Vector2(100, 100);
        _wheel.Scale = 0.3f;
        base.Initialize();
    }

Solution

  • Can you use a list? You may need to include this:

    using System.Collections.Generic;
    
    //Somewhere in the class
    List<Wheel> myWheels = new List<Wheel>();
    
    // In your method
    var _wheel = new Wheel();
    
    // Set your properties
    
    myWheels.Add(_wheel);
    
    //Then when needed, you can loop like this:
    foreach(var wheel in myWheels)
    {
         // do something with wheel...
    }
    

    I don't do XNA, but this is fairly common in C#.