XNA-获取C#错误
我在XNA做游戏。目前我正在研究碰撞检测。我无法从代码中解决以下两个错误:XNA-获取C#错误,c#,xna,C#,Xna,我在XNA做游戏。目前我正在研究碰撞检测。我无法从代码中解决以下两个错误: // Non-static variables exist once for each instance of the class Vector2 meteorPos; // Static variables are shared between all instances of a class public static Texture2D meteorTexture; public Vector2 meteorPo
// Non-static variables exist once for each instance of the class
Vector2 meteorPos;
// Static variables are shared between all instances of a class
public static Texture2D meteorTexture;
public Vector2 meteorPosPub { get { return meteorPos; } }
// Line that contains the errors
public static Rectangle boundingBox = new Rectangle((int)meteorPosPub.X, (int)meteorPosPub.Y, (int)meteorTexture.Width, (int)meteorTexture.Height);
public meteorGenerator(Vector2 pos)
{
this.meteorPos = pos;
}
以下是错误:
An object reference is required for the non-static field, method, or property 'SpaceInvaders.meteorGenerator.meteorPosPub.get'
An object reference is required for the non-static field, method, or property 'SpaceInvaders.meteorGenerator.meteorPosPub.get'
您的
boundingBox
字段是静态的,但您试图访问的meteopospub
不是静态的。boundingBox
需要是非静态的,这将修复该错误
请记住,非静态成员可以访问静态成员,但静态成员不能访问非静态成员。如果你仔细想想,这是有道理的。流星的位置对于物体的每个实例都是不同的
您还需要将字段的初始化移到构造函数中,因为您现在尝试访问meteorPosPub时,meteorPosPub的值未知:
...
public Rectangle boundingBox;
public meteorGenerator(Vector2 pos)
{
this.meteorPos = pos;
this.boundingBox = new Rectangle((int)meteorPosPub.X, (int)meteorPosPub.Y, meteorTexture.Width, meteorTexture.Height);
}
@查理啊,你说得对。我已经更新了我的答案来解决这个问题。我也想到了,但是我如何从其他类访问
boundingBox
?@Charlie,就像你访问MeteoposPub一样。类似于流星发生器流星=新流星发生器(Vector2.Zero);流星包围盒代码>最佳实践是创建一个boundingBox属性,而不是一个公共字段,但每次只能创建一个挑战。