I’m trying to draw a tile map in C# and the problem I’m having is strange in my opinion.
I have this int array that is suposed to hold the x coordinate and y coordinate to draw the tiles on the screen. (The arrow with not only 0’s in it is X and other one is Y)
int[,] level1 = { { 0, 32, 64, 96 }, { 0, 0, 0, 0 } };
Here is how I use for loops to render a part of the tile into the screen and it’s here I’m getting an “OutOfMemoryException” on a line that I will comment out:
public void DrawTest(SpriteBatch spriteBatch)
{
for (int x = 0;; x++)
{
for (int y = 0;; y++)
{
x = level1[x, 0];
y = level1[0, y];
//This line bellow is where it says OutOfMemoryException
spriteBatch.Draw(tileSheet, new Rectangle(x, y, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
if (x >= 5 | y >= 5)
{
x = 0;
y = 0;
}
}
}
}
When i want to call this render method i do it in the main class Render method
levelLoader.DrawTest(this.spriteBatch);
It worked perfectly before i used this DrawTest method to try drawing the tiles. But I have completely no idea why this isn’t working correctly.
UPDATE:
public void DrawTest(SpriteBatch spriteBatch)
{
for (int x = 0; x < 5 ; x++)
{
for (int y = 0; y < 5 ; y++)
{
x = level1[x, 0];
y = level1[0, y];
spriteBatch.Draw(tileSheet, new Rectangle(x, y, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
}
}
}
UPDATE2:
public void DrawTest(SpriteBatch spriteBatch)
{
for (int x = 0; x < 5 ; x++)
{
for (int y = 0; y < 5 ; y++)
{
int tileXCord = level1[x, 0];
int tileYCord = level1[0, y];
spriteBatch.Draw(tileSheet, new Rectangle(tileXCord, tileYCord, 32, 32), new Rectangle(0, 0, 32, 32), Color.White);
}
}
}
I see several problems in your code:
spriteBatch.Draw()method doesn’t draw anything, it just schedules the drawing of your sprites. This method invocation should be preceded byspriteBatch.Begin()(to start scheduling he drawing) and eventually you must callspriteBatch.End()to flush the scheduled spites to your device. You infinite loops cause the infinite scheduling of your sprite drawing until the memory is full and you are facing the out of memory exception.(x >= 5 | y >= 5)you are using a bitwise OR comparison, you shouldn’t do it (unless on purpose, which I don’t see here and rather use boolean OR:(x >= 5 || y >= 5)I would re-write your code this way
It will re-draw all your tiles on every
Draw()event of the main gameloop (provided you are still calling this method from yourDraw()method of yourGameclass. XNA varies the FPS rate depending upon the performance of you PC and the amount of calculation it has to be done on every frame.