Search code examples
c#xnahlsl

Draw effect XNA with multiple texture


In Xna I would like to draw my model with a custom effect.. SO I would like to get the textures from the mesh.

 foreach (ModelMesh mesh in model.Meshes)
            {

                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    

                    effect.Parameters["World"].SetValue(World );
                    effect.Parameters["View"].SetValue(View);
                    effect.Parameters["Projection"].SetValue(Projection);
                    effect.Parameters["TextureEnabled"].SetValue(true);

                    
                    
                    var basicEffect = part.Effect as BasicEffect;
                    if (basicEffect != null)
                    {
                        Texture2D texName = basicEffect.Texture;
                        effect.Parameters["Texture"].SetValue(texName);

                    }

                    part.Effect = effect;

                }
                mesh.Draw();

            }

the model is black if I run this code.. but if I remove the if (basicEffect != null) it appears correctly for 1 fram but then a Null exception appears.

Thank you


Solution

  • I was finally able to get it right by changing the code to that:

            Texture2D[] texts =  new Texture2D[40000];
            bool bol = true;
            public void DrawModel( camera cam)
            {
    
               
    
                int i = 0;
                foreach (ModelMesh mesh in model.Meshes)
                {
    
                    foreach (ModelMeshPart part in mesh.MeshParts)
                    {
                        effect.Parameters["World"].SetValue(World );
                        effect.Parameters["View"].SetValue(View);
                        effect.Parameters["Projection"].SetValue(Projection);
                        effect.Parameters["TextureEnabled"].SetValue(true);
    
    
                        
                        var basicEffect = part.Effect as BasicEffect;
                        if (bol && basicEffect != null)
                        {
                            texts[i] = basicEffect.Texture;
                        }
    
                        
                        effect.Parameters["Texture"].SetValue(texts[i]);
                        i++;
    
                        part.Effect = effect;
                    }
                    mesh.Draw();
    
                }
                bol = false;
            }