在我的主类中,我有一个“实体”对象列表,实体是我创建的一个类,其中包含玩家和/或敌人所需的所有必要数据。
List<Entity> Listentities = new List<Entity>();
再往下,我有我的重力方法,在目前的状态下有一些问题。
public void Gravity(GameTime gameTime)
{
foreach(Entity entity in Listentities)
{
entity.entityPosition.X += 1;
}
}
我在这里尝试做的事情非常简单;每次调用该方法时,我都会尝试获取列表中的每个实体并将其 position.X 向下移动一个单位。但是,每次我运行游戏时,我都会在线获得“对象引用未设置为对象的实例”
entity.entityPosition.X += 1;
我需要知道我做错了什么。虽然我学得很快,但我还是很新。现在,只有一个实体被添加到列表中,实体“player1”。我可以通过键入轻松修复此错误
player1.entityPosition.X += 1;
但这只会影响玩家。
编辑:我包括实体的构造函数:
public Entity(string entityName, Texture2D EntityAppearance, int EntityMaxHealth, int SpriteHeight, int SpriteWidth, int CurrentFrame, int AnimationCall, int EntityAttack, int EntityStr, int EntityDex, int EntityLuk, int EntityDefense, bool EntityIsMe )
{
this.entityName = entityName;
this.EntityAppearance = EntityAppearance;
this.EntityMaxHealth = EntityMaxHealth;
this.SpriteHeight = SpriteHeight;
this.SpriteWidth = SpriteWidth;
this.CurrentFrame = CurrentFrame;
this.AnimationCall = AnimationCall;
this.EntityAttack = EntityAttack;
this.EntityLuk = EntityLuk;
this.EntityDex = EntityDex;
this.EntityStr = EntityStr;
this.EntityDefense = EntityDefense;
this.EntityIsMe = EntityIsMe;
}
和 game1 中的 loadcontent() 方法。
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
camera = new Camera(GraphicsDevice.Viewport);
player1 = new Entity("player1", Content.Load<Texture2D>("PlaceHolder"), 100, 100, 100, 0, 0, 3, 1, 1, 1, 0, true);
player1.EntityPosition = new Vector2(0, 0);
player1.EntityBox = new Rectangle((int)player1.EntityPosition.X, (int)player1.EntityPosition.Y, player1.SpriteWidth, player1.SpriteHeight);
player1.Origin = new Vector2();
spritefont = Content.Load<SpriteFont>("SpriteFont1");
}
以及我的 Entity 类顶部的 entityPosition 变量。
public Vector2 entityPosition;
public Vector2 EntityPosition
{
get { return entityPosition; }
set { entityPosition = value; }
}
列表的初始化:
List<Entity> Listentities = new List<Entity>();
这是game1.cs的顶部
我将 player1 实体添加到 Listentities 的代码:
protected override void Initialize()
{
InitGraphicsMode(1280, 720, false);
Listentities.Add(player1);
base.Initialize();
}
当然在 Game1 中。
也许我也应该提到我正在使用 XNA GS 4.0