C#XNA非静态字段、方法或属性需要对象引用



我正在尝试创建egg spawner,但出现了此错误
我试图修正这个错误,但不幸的是我不能
我知道XNA框架已经过时了,但我用它来学习

有人能帮我吗
谢谢。

代码:

public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
int screenWidth;
int screenHeight;
List<Eggs> eggList = new List<Eggs>();

public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.IsFullScreen = false;
graphics.PreferredBackBufferHeight = 600;
graphics.PreferredBackBufferWidth = 800;
Content.RootDirectory = "Content";
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);

screenWidth = GraphicsDevice.Viewport.Width;
screenHeight = GraphicsDevice.Viewport.Height;

}
public class Eggs
{
public Texture2D texture;
public Vector2 position;
public Vector2 velocity1;

public bool isVisible = true;

Random random = new Random();
int randX;

public Eggs(Texture2D newTexture, Vector2 newPosition)
{
texture = newTexture;
position = newPosition;

randX = random.Next(0, 400);
velocity = new Vector2(randX, 0);
}

public void Update(GraphicsDevice graphic)
{
position += velocity;

if(position.Y < 0 - texture.Height);
isVisible = false;
}

public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, Color.White);
}
}
float spawn = 0;
protected override void Update(GameTime gameTime)
{
spawn += (float)gameTime.ElapsedGameTime.TotalSeconds;

foreach(Eggs eggList in eggList)
eggList.Update(graphics.GraphicsDevice);

LoadEggs();
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
Exit();
base.Update(gameTime);
}

public void LoadEggs()
{
if(spawn >= 1)
{
spawn = 0;
if(eggList.Count() < 4)
eggList.Add(new Eggs(Content.Load<Texture2D>("Images/egg"), new Vector2(50, 0)));
}

for(int i = 0; i < eggList.Count; i++)
if(!eggList[i].isVisible)
{
eggList.RemoveAt(i);
i--;
}
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.LightYellow);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
foreach(Eggs eggList in eggList)
{
Eggs.Draw(spriteBatch);
}
spriteBatch.End();
base.Draw(gameTime);
}
}

为什么会出现这种错误?

错误CS0120:非静态字段、方法或属性"Game1.E"需要对象引用ggs。Draw(SpriteBatch('

似乎是6。这条线从末端开始制造问题。Eggs.Draw(SpriteBatch)不能这样调用。由于Eggs不是静态类,Draw也不是静态方法,这意味着您需要Eggs类型的对象来调用Draw方法。

所以需要这样的东西:

var egg = new Eggs();
egg.Draw(SpriteBatch);

此外,foreach循环并没有意义,不要为项使用相同的名称,因为它是循环通过的集合的名称。

绘图中的foreach循环:

foreach(Eggs eggList in eggList)
{
Eggs.Draw(spriteBatch);
}

应更改为:

foreach(Eggs egg in eggList)
{
egg.Draw(spriteBatch);
}

正如Luka所说,它目前直接从类中调用,而类通常只适用于静态类和方法。

我只是认为声明一个新的变量是没有必要的,因为你想循环遍历列表中的鸡蛋,而不是创建一个空的类。因此,现在它从foreach中的egglist声明一个egg,并使用该egg来调用中的draw函数。

相关内容

最新更新