Array with a variable instead of a number

in my program I have the following code:

int Blockers = 4;
Texture2D mTexture;
Texture2D[] tBrick = new Texture2D[Blockers];

so anyway, this gives me the following error
"A field initializer cannot reference the nonstatic field, method, or property " , underlining the Blockers word in the 3rd line of code above.

I also have several other lines similar to this one declaring Integer arrays, which give me the same error.

The only reason I'm trying to do this is to make it more 'Dev friendly' so that anyone can just change the number of 'Blockers' and create more bricks in my game.


;




Answer this question

Array with a variable instead of a number

  • mwoehlke

    If it is only for development purposes, just replace

    int Blockers=4;

    with

    const int Blockers=4;

    Making it a constant lets you use it in the array size declaration, but of course you can't change it at run time.


  • Evidica

    You're doing that outside of a method, aren't you You should do something like:

    int Blockers = 4;
    Texture2D mTexture;
    Texture2D[] tBrick

    private void InitializeBricks(){

    tBrick = new Texture2D[Blockers];

    }

    I can't test it right now, but I think it should work.


  • Venkata Prasad K

    Thanks... almost embarrassing to get such a simple answer

    Thanks again!



  • Array with a variable instead of a number