Search code examples
arraysinstancemonogame

Something like dynamic array


Guy please I want to do something like dynamic array but I don't want to use List.

public Texture2D[] spritHouses; 
protected override void LoadContent()
{
    LoadTextures(spritHouses, @"Sprits/Guns/", "Big", "Medium", "Small");
    //The array spritHouses is still null...
}
public void LoadTextures(Texture2D[] texture, string trace, params string[] names)
{
    texture = new Texture2D[names.Count()];
    for (int i = 0; i <= names.Count()-1; i++)
        texture[i] = Content.Load<Texture2D>(trace + names[i]);
}

Why the creating of new instance doesn't work?


Solution

  • First, it's not really clear why you don't want to use List.

    Although, based on your code I assume what you really mean is that you want to create an array of textures from a hard coded array of strings (texture names).

    But before I show you another way, let me explain why spriteHouses is still null.

    When you pass the spritHouses as parameter to the LoadTextures method, what you're actually doing is passing a copy of the "value" (i.e. null) to the method. This means that the texture variable will be null at the start of the method, but then you're assigning it a new value of new Texture2D[names.Count()];.

    At this point the texture variable has what you want, but when the method returns, this local copy of the array is thrown away and spriteHouses is still null. Does that make sense?

    Anyway, the simple fix is to return the new array instead of passing it in as a parameter.

    public Texture2D[] spritHouses; 
    
    protected override void LoadContent()
    {
        spritHouses = LoadTextures(@"Sprits/Guns/", "Big", "Medium", "Small");
    }
    
    public Texture2D[] LoadTextures(string trace, params string[] names)
    {
        var textures = new Texture2D[names.Count()];
    
        for (int i = 0; i <= names.Count()-1; i++)
            textures[i] = Content.Load<Texture2D>(trace + names[i]);
    
        return textures;
    }