如何在同一个类中引用main方法之外的对象?

时间:2014-02-10 01:07:21

标签: c# sfml

在使用C#和图形库SFML创建游戏的过程中,我遇到了错误“当前上下文中不存在名称'战斗机'”。我不确定如何在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
            };
            ...
        }

    }
}

1 个答案:

答案 0 :(得分:1)

我不确定你是否意味着这样的实现,你能试试这段代码吗?

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
            };
            ...
        }

    }
}