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

标签 c# sfml

在使用 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/

相关文章:

c++ - SFML 2.1 被按下

c++ - 警告 C26812 : Enum type is unscoped. 优先选择枚举类而不是枚举

c++ - "Looking At"具有四元数的对象

c# - 使用 LINQ 选择本周

c# - 检查网络驱动器上是否存在目录

c# - 使用 INNER JOIN 时出现意外的数据库输出

C# Date Parse 非标准日期格式

c++ - 为什么非常大的 If 语句会导致堆栈溢出

c++ - 尝试使用 SFML 时出错(一些 LNK 错误)

c# - 错误 APPX3212 : SDK root folder for 'Portable 7.0' cannot be located