Search code examples
c#texturesxna-4.0

Drawing different Textures with a single Basic Effect, XNA 4.0


I have a problem in the game I wrote with XNA. I recently added Textured polygons, and saw that every textured polygon shared the same texture although I changed it before calling. The code I am using:

      if (countMeshes > 0)
        {

            for (int i = 0; i < countMeshes; i++)
            {

                TexturedMesh curMesh = listMeshes[i];

                if (curMesh.tex == null)
                {

                    drawEffect.Texture = WHITE_TEXTURE;

                }
                else
                {
                    drawEffect.Texture = curMesh.tex;
                }

                drawEffect.Techniques[0].Passes[0].Apply();
                graphics.DrawUserPrimitives(PrimitiveType.TriangleList, curMesh.verts, 0, curMesh.count);

            }
        }

Now, the first that came into my mind would be to create a BasicEffect for each Texture I need to draw. But I think that would be a bit of a overkill so my question is: How should I do it?

PS: I double checked everything, the UV Coords are fine, and it is 2D.


Solution

  • It seems to be the only way, the way I did it was to create a Dictionary with the texture as the key and a struct of a basic effect and a list of Vertexs as the value.

    Something like this:

    public struct MeshEffect
    {
    
        public TexturedMesh mesh;
        public BasicEffect effect;
    
    }
    

    and the Dictionary:

     private Dictionary<Texture2D, MeshEffect> texturedMeshes = new Dictionary<Texture2D, MeshEffect>();
    

    But it all really depends on how you handle drawing, but one thing is sure, you can't use more than one texture on one BasicEffect.