質問

In the process of creating a game using C# and the graphics library SFML, I encountered the error "The name 'fighter' does not exist in the current context". I am unsure of how to refer to the object in the SFML static event method MouseButtonPressed(), as it returns the above error.

I am aware that you could declare the object as static, as I have done (and commented out below) in the code. However, throughout the game, an unknown number objects will be created, and so I don't think you make multiple instance fields. What is the best approach?

Relevant code:

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

    }
}
役に立ちましたか?

解決

I'm not sure if this's such implementation you mean, could you try this code?

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

    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top