Problems with laggy c # code in xna game studio

My code seems to have compiled, but when I try to run it, it hangs a lot.

I am following the REMER XNA tutorial here .

I am well acquainted with C #, but by no means an expert. I had no problems getting this to work up to this point, and there are no errors or exceptions that arise ... it just freezes. I read on its related forum, where users discussed other problems, usually related to typos or code errors, but there is nothing like that there ... It seems that everyone can work fine.

Perhaps I did something wrong? The nested loop at the bottom looks a little heavy for me. screenWidth and screenHeight are 500 and 500.

BTW: this starts from the LoadContent override method, so it should only work once as far as I know.

private void GenerateTerrainContour() { terrainContour = new int[screenWidth]; for (int x = 0; x < screenWidth; x++) terrainContour[x] = screenHeight / 2; } private void CreateForeground() { Color[] foregroundColors = new Color[screenWidth * screenHeight]; for (int x = 0; x < screenWidth; x++) { for (int y = 0; y < screenHeight; y++) { if (y > terrainContour[x]) foregroundColors[x + y * screenWidth] = Color.Green; else foregroundColors[x + y * screenWidth] = Color.Transparent; fgTexture = new Texture2D(device, screenWidth, screenHeight, false, SurfaceFormat.Color); fgTexture.SetData(foregroundColors); } } } 
+4
source share
2 answers

Perhaps something has to do with the fact that you are creating 250,000 screen-sized textures (holy mole)!

Resource allocation is always difficult - especially when you are dealing with tools such as sounds and images.

It seems you really only need one texture, try moving fgTexture = new Texture2D(device, screenWidth, screenHeight, false, SurfaceFormat.Color); outside of the loop. Then try moving fgTexture.SetData(foregroundColors); out of cycle.

 private void CreateForeground() { Color[] foregroundColors = new Color[screenWidth * screenHeight]; fgTexture = new Texture2D(device, screenWidth, screenHeight, false, SurfaceFormat.Color); for (int x = 0; x < screenWidth; x++) { for (int y = 0; y < screenHeight; y++) { if (y > terrainContour[x]) foregroundColors[x + y * screenWidth] = Color.Green; else foregroundColors[x + y * screenWidth] = Color.Transparent; } } fgTexture.SetData(foregroundColors); } 
+6
source
 for (int x = 0; x < screenWidth; x++) { for (int y = 0; y < screenHeight; y++) { if (y > terrainContour[x]) foregroundColors[x + y * screenWidth] = Color.Green; else foregroundColors[x + y * screenWidth] = Color.Transparent; } } foregroundTexture = new Texture2D(device, screenWidth, screenHeight, false, SurfaceFormat.Color); foregroundTexture.SetData(foregroundColors); 

Your problem is with the last two lines. In your loop, you create 500 x 500 Texture2D , which slows you down. Move them outside the for loop.

+3
source

All Articles