问题描述
我正在用 XNA 4.0 制作游戏,但我真的不了解效果和基本效果.
I'm making a game in XNA 4.0 and I really don't understand the effect and basiceffect stuff.
我目前有这个:
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;
}
所以我把这段代码放在了我的 foreach (BasicEffect effect in mesh.Effects)
之前,但它不起作用,这是在这一行抛出的错误 foreach (BasicEffect effect in mesh.Effects)
.Effects):
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)
:
无法将Effect"类型的对象转换为BasicEffect"类型.
我真的迷路了...
推荐答案
我在 XNA 方面做得并不多,但这是一个基本的 C# 问题.
I haven't done much with XNA but this is a basic C# question.
正如错误所说,您正在尝试遍历 mesh
的 Effects
,但您将它们全部转换为 BasicEffect
实例.BasicEffect
是 Effect
的子类,并非您添加的所有效果都属于 BasicEffect
类型.所以演员表失败了.
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.
理想情况下,您应该在添加 BasicEffect
对象之前设置它们的属性,而不是迭代 Effects
属性,但不了解更多关于您的代码,我能建议的最好是做这样的事情:
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).
这篇关于XNA 在 BasicEffect 上应用效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!