I trying to use the SetData method as a part of a pixel based Collision Detection mechanism I use in my game.
In general, I want to set a texture’s overlapping pixels to transparent.
While trying to use the SetData I keep receiving the following exception:
“You may not call SetData on a resource while it is actively set on the GraphicsDevice. Unset it from the device before calling SetData.”
I did manage to find some almost similar questions dealing with this exception in StockOverFlow, yet I am still not sure how to deal with this Exception:
- I’ve tried to call SetData from the Draw method, yet the Exception keeps appearing.
- I’ve tried to understand whether I should somehow remove the texture from the GraphicsDevice, but the only way to do this seems to be using the texture’s index in GraphicsDevice.Textures[idx] and set it to null. What if I don’t hold this index in my class?
My game, naturally I think, holds multiple textures inside it (Some of them are added to Game.Components as well). Perhaps this might be the root of the problem?
I am attaching a very small part of my code… I don’t see a real reason to post more than that.
private void collisionDetected()
{...
for (int col = collisionLeftCordinate; col < collisionRightCordinate; col++)
{
for (int row = collisionTopCordinate; row < collisionBottomCordinate - 1; row++)
{
if (m_BarrierPixels[col + row * (int)this.Texture.Width] != Color.Transparent)
{
m_BarrierPixels[col + row * (int)this.Texture.Width] = Color.Transparent;
m_TransparentPixelsCounter++;
}
}
}
this.Texture.SetData(m_BarrierPixels);
...}
collision detection over Pixel’s are not efficient, you have to cold color arrays, where you have to care about scale and rotation factors.
if you are working on renderTarget’s you should set renderTarget to null, so that you can change the pixel, if you are not using renderTarget, you should change the pixel in Update (which is better) if you want to do it in Draw method, then you should call is before spriteBatch.Begin .