开发者

How to make enum accessible from other classes in XNA when enum is defined in main game class?

So I have my main game class and have created an enum for game state. How do I make this enum accessible to other classes? I know you have to make it public but I cant seem to make it accessible to other classes. What I'm trying to do is have a bunch of different classes to开发者_如何学Go be able to check the current game state via enum and do different things depending on the current game state.


There are two main ways to do this.

  1. Make the game state globally accessible, either through a global variable or a singleton.
  2. Pass a game state supplier object to the objects needing to know the game state.

I prefer option 2 as it makes your dependencies more explicit.

public enum GameState
{
   Running,
   Paused
}

public interface IGame
{
   GameState State { get; }
}

public class SomeObject
{
   private IGame m_game;

   public SomeObject(IGame game)
   {
      m_game = game;
   }

   public void Update()
   {
      switch (m_game.State)
      {
         case GameState.Running:
            UpdateRunning();
            break;

         case GameState.Paused:
            UpdatePaused();
            break;
      }
   }
}

public class Game : IGame
{
   GameState m_state;
   SomeObject m_object;

   public Game()
   {
      m_object = new SomeObject(this);
      m_state = GameState.Running;
   }

   public GameState State
   {
      get
      {
         return m_state;
      }
   }
}

However, exposing your game state to an object other than the game should be avoided if possible. It breaks the encapsulation of your game and tightly couples your objects together. Do the objects really need to know your game state or is there a more specific thing they need to know in order to operate? Can you have two separate objects, one corresponding to each game state that are controlled by the game class?


depending on what namespace it's in, you might have to place the following line (or one similar) at the top of any .cs file that you want to have access to it:

using MyGame.ThisIsMyNameSpace;

That exposes the enum so that you can reference it without having to fully qualify it

or, if what you mean is that you need a way to access the current game's state, then you need to have a reference to something. One thing that many people do is make a public property on the Game class, and then pass around a reference to that instance. Other people just make a singleton or static class to hold that globally available space. It all depends on your code style and the size of your game


public class GameClass
{
    public static GameState State;
}

This means there will only be one instance of State regardless of how many GameClass instances you create, but it seems like that'd be desired behavior in this case. You can access it with GameClass.State instead of gameClassInstance.State

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜