MaterialShader change affects multiple objects

Sep 14, 2010 at 3:00 PM
Edited Sep 14, 2010 at 3:11 PM

I am making a breakout game as a way to familiarize myself with XNA and Xen, and I have just stumbled upon an issue
with using shaders.

I have ~100 bricks created randomly on the level. Each brick is a Xen.Ex.Geometry.Cube.

In the initalize function of Brick i set up the shader to use with this code:

MaterialShader material = new MaterialShader();
material.Lights = new MaterialLightCollection();
material.Lights.AmbientLightColour = new Color(100, 100, 100).ToVector3();
material.TextureMap = _texture;

model.SetShaderOverride(new ModelInstanceShaderProvider<MaterialShader>(material));

When the ball hits a brick, the brick changes color based on how much life it has:

switch (lives) {
       case 1:
            shader.DiffuseColour = Color.Green.ToVector3();
            break;
       case 2:
           shader.DiffuseColour = Color.Orange.ToVector3();
           break;
//        (...)
     default:
          shader.DiffuseColour = Color.BlueViolet.ToVector3();
          break;
}


Ok, so all is good this far. The bricks all start at different colors based on their life (random),
and they change colors when they are hit. The lighting is very flat however, so I want to add some
lights. I add the following line to Initialize():

material.Lights.AddDirectionalLight(true, new Vector3(-1, 0, 1), Color.White);

When I start the game now, all bricks start out with the same color. Whenever I hit a brick and it
changes colour, 30-100% of the other bricks change color as well.

Do all the bricks use the same shader instance? And is there a way I can avoid this?

Screenshots:

Ok start
Bugged start
Bugged after hit