Hi! I’m quite new to monogame I use it on a school project, I have a problem with RenderTarget2D and SetRenderTarget. I have a map class:
public class Map
{
private RenderTarget2D _target;
public const int TILE_SIZE = 128;
public static readonly int[,] tiles = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 1, 0, 1, 0, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 0, 1, 0, 1, 0, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 0, 1, 0, 1, 0, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
};
Texture2D wall = Globals.Content.Load<Texture2D>("wall");
public Map()
{
_target = new(Globals.GraphicsDevice, tiles.GetLength(1) * TILE_SIZE, tiles.GetLength(0) * TILE_SIZE);
Activate();
DrawMap();
Globals.GraphicsDevice.SetRenderTarget(null);
}
public void Explosion()
{
tiles[0,0] = 0;
Activate();
DrawMap();
Globals.GraphicsDevice.SetRenderTarget(null);
}
public void Activate(){
Globals.GraphicsDevice.SetRenderTarget(_target);
Globals.GraphicsDevice.Clear(Color.Transparent);
}
public void DrawMap(){
Globals.SpriteBatch.Begin();
for (int i = 0; i < tiles.GetLength(0); i++)
{
for (int j = 0; j < tiles.GetLength(1); j++)
{
if (tiles[i, j] == 1)
{
var posX = j * TILE_SIZE;
var posY = i * TILE_SIZE;
Globals.SpriteBatch.Draw(wall, new Vector2(posX, posY), Color.White);
}
}
}
Globals.SpriteBatch.End();
}
public void Draw()
{
Globals.SpriteBatch.Draw(_target, Vector2.Zero, Color.White);
}
public void Update()
{
}
}
In my GameManager classes Init method which is called in the LoadContent method of Game1 class, I make a map instance. And it works fine, until I try to redraw the map layout because an explosion happens, but my game crashes at line Globals.GraphicsDevice.SetRenderTarget(_target); in Activate(). I got Exception thrown: ‘System.InvalidOperationException’ in MonoGame.Framework.dll; message in the debug console. Any idea what causing it or what am i missing?
Any answears are appreciated!