Kallum Burgin
Kallum Burgin

Reputation: 103

Can't assign value to an array

I have an array of tiles that are of the type Texture2D and want to set each one in the array to something different.

for (int i = 1; i <= columns * rows; i++)
        {
            m_tiles[i] = new Texture2D(m_graphicsDevice, tilewidth, tileheight);
        }

It points to the error being the closing }

I don't understand how it being null when I'm trying to set it to not be null effects it. If I can never set the variable to anything then they'll always be null.

I have tried:

Texture2D[] m_tiles = new Texture2D(m_graphicsDevice, tilewidth, tileheight)[500];

But the compiler says "Cannot apply indexing with [] to and expression of type 'Microsoft.Xna.Framework.Graphics.Texture2D'"

Upvotes: 1

Views: 1705

Answers (3)

Patrick Desjardins
Patrick Desjardins

Reputation: 140753

You need to initialize the array with a proper dimension.

m_tiles[] may not be initialized to receive (columns * rows) elements.

So, before your loop, you should initialize the m_titles array with this size.

Texture2D[] m_tiles = new Texture2D[columns * rows];

So, if you have 1 columns and 1 rows, it will give you 1 slot (m_tiles[0]). If you have 2 columns and 2 rows you will have 4 slots (m_tiles[0],m_tiles[1],m_tiles[2],m_tiles[3]);

You should start you loop with i = 0 otherwise, the [0] won't be assigned and an exception of index out of bound will be trigged. If you really do not want to start with 0, you can increase by 1 the size of the array using (columns * rows +1).

Upvotes: 0

Yannick Motton
Yannick Motton

Reputation: 35971

You'll first need to initialize an array instance in order to assign values to its elements:

Preceed the for-loop with following statement:

Texture2D[] m_tiles = new Texture2D[columns * rows + 1];

Arrays indices are 0-based in C#, and afaik most .NET languages. So when using the indexer, you might want to loop from 0 .. n-1, instead of 1 .. n.

But honestly, I rarely ever still use arrays in .NET. If you have no specific reason to use an array, I would recommend to use a List<T> :

List<Texture2D> m_tiles = new List<Texture2D>();
for(;;)
{
  m_tiles.Add(new Texture2D(foo, bar));
}

Upvotes: 2

CodingGorilla
CodingGorilla

Reputation: 19842

You need to instantiate the array first, like:

m_tiles = new Texture2D[10];

Like most other types, arrays need to be created, more specifically it needs to know how many elements you want it to have (in this case, it has 10 "slots").

Upvotes: 1

Related Questions