3
\$\begingroup\$

i want to be able to loop through a hole bunch of textures, and render them on an object. I then want the rendered image to be placed onto a texture2D.

The point? well hopefully i will end up with an array of Texture2D's containing a model with multiple skins.

Here's my code:

        for (byte i = 1; i < allBlockIso.Count(); i++)
        {
            DisplayBox.SetValue(i);
            GraphicsDevice.SetRenderTarget(cubeTarget);
            GraphicsDevice.Clear(Color.Transparent);
            DrawIsoCube();
            GraphicsDevice.SetRenderTarget(null);
            allBlockIso[i] = (Texture2D)cubeTarget;
        }

DisplayBox.SetValue is a function which goes through and sets the texture. This is working! DrawIsoCube() draws the cube (the test model) and this is working too. The problem is definitely something to do with the unreusability of the render target.

Pretty simple yet it's not working. It appears that whatever the last image being rendered is, is shown in every image of the allBlockIso array.

Anyone know a fix? Cheers.

P.S. sorry if this wan't explained well. I'm not very good at explaining :P

\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

A RenderTarget2D is also a Texture2D. You don't ever "convert" it to a texture - it simply already is a texture. So you're simply passing the one object around and reusing it.

(You can prove this in the Debugger by giving the object a marker - you will see that every texture in your array is the same object!)

So you have two options:

  • You could create multiple RenderTarget2D objects and use one for each texture.

  • You could create multiple Texture2D objects, and copy your render target into a texture, using the GetData and SetData functions, after each time you render to it. (Your data will have to go through (copied into and then copied out of) a buffer, which you can reuse because it is not used in the final result.)

If you are doing this while your game is running (it is happening each frame or frequently), you should probably use the first approach. If you are doing this at load time (it happens once or occasionally), then you should probably use the second approach.

See also this question.

Also look into the difference between value types and reference types (see this document for lots of information about the .NET type system). Texture2D is a reference type, which means that the variable you hold is a reference to the object - not the object itself.

\$\endgroup\$
1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .