質問

I'm making a game in XNA 4.0 and I really don't understand the effect and basiceffect stuff.

I currently have this:

foreach (ModelMesh mesh in model.Meshes)
{
    foreach (BasicEffect effect in mesh.Effects)
    {
        if (mesh.Name != collisionShapeName)
        {
            effect.TextureEnabled = true;

            effect.Texture = _textures[name];

            effect.SpecularColor = new Vector3(_specularColor);
            effect.SpecularPower = 32;
        }
    }
}

And I have found a tutorial for rendering shadow and I need to apply this code on mine:

foreach (ModelMesh mesh in model.Meshes)
{
    foreach (ModelMeshPart part in mesh.MeshParts)
        part.Effect = material.effect;
}

So I put this code before my foreach (BasicEffect effect in mesh.Effects), but it doesn't work, here's the error thrown on this line foreach (BasicEffect effect in mesh.Effects):

Unable to cast object of type 'Effect' to type 'BasicEffect'.

I'm really lost here...

役に立ちましたか?

解決

I haven't done much with XNA but this is a basic C# question.

As the error says, you're trying to iterate over the Effects of your mesh but you're casting them all to BasicEffect instances. BasicEffect is a subclass of Effect and not all of the effects that you're adding are of type BasicEffect. So the cast fails.

Ideally, you'd set the properties of the BasicEffect objects before they're added, rather than iterating over the Effects property, but without knowing any more about your code, the best I can suggest would be to do something like this:

foreach (Effect effect in mesh.Effects)
{
    var basicEffect = effect as BasicEffect;
    if (basicEffect != null)
    {
        // Do some stuff with basicEffect
    }
}

Normally this kind of downcasting is indicative of some flaw elsewhere in your code structure but it may be the best you can do in your scenario (and it's impossible to suggest anything better without a deeper understanding of your code).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top