在使用 C# 和图形库 SFML 创建游戏的过程中,我遇到了“名称‘fighter’在当前上下文中不存在”的错误。我不确定如何在 SFML 静态事件方法 MouseButtonPressed() 中引用该对象,因为它会返回上述错误。
我知道您可以像我在代码中所做的那样(并在下面注释掉)将对象声明为静态的。但是,在整个游戏中,将创建未知数量的对象,因此我认为您不会创建多个实例字段。 什么是最好的方法?
相关代码:
namespace Game
{
public class Program
{
//I don't want to have to do this
//static Unit fighter;
Texture textureFighter;
static void MouseButtonPressed(object sender, MouseButtonEventArgs e)
{
if (e.Button == Mouse.Button.Left)
{
fighter.Move(new Vector2f(Mouse.GetPosition().X, Mouse.GetPosition().Y));
}
}
public static void Main()
{
Program myProgram = new Program();
myProgram.textureFighter = new Texture(@"resources\ship_fighter.png");
Unit fighter = new Unit(new Vector2f(100, 100), 0)
{
Texture = myProgram.textureFighter
};
...
}
}
}
最佳答案
我不确定这是否是您的意思,您可以试试这段代码吗?
namespace Game
{
public class Program
{
static Program myProgram = new Program();
Unit fighter;
Texture textureFighter;
static void MouseButtonPressed(object sender, MouseButtonEventArgs e)
{
if (e.Button == Mouse.Button.Left)
{
myProgram.fighter.Move(new Vector2f(Mouse.GetPosition().X, Mouse.GetPosition().Y));
}
}
public static void Main()
{
myProgram.textureFighter = new Texture(@"resources\ship_fighter.png");
myProgram.fighter = new Unit(new Vector2f(100, 100), 0)
{
Texture = myProgram.textureFighter
};
...
}
}
}
关于c# - 如何在同一个类的main方法之外引用一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21667453/