在XNA中,如何从另一个类中修改主游戏类中的某些内容?

时间:2013-01-22 02:17:56

标签: c# xna

好的,默认情况下,XNA PC游戏的Game类有一个名为IsMouseVisible的公共bool属性,当设置启用/禁用鼠标可见时。我有另一个名为Configs的类,它监视被按下的特定键。现在我想要做的就是设置它,这样当我按下一个特定的键时,它将改变IsMouseVisible的值。这是我卡住的地方,因为我不知道如何更改另一个类的值。

我知道我可以在Configs类中创建一个bool值,并使其在按下键时,值会改变,然后使其成为主Game时的值类更新,它将IsMouseVisible的值设置为Configs类的值,但问题是,我可能想要创建可以在main {中设置的多个不同的值(不仅仅是IsMouseVisible){来自另一个类的{1}}类。

还有我的问题,我如何在另一个班级的主Game课程中设置一些东西? (无需为我想要访问的每个值创建多个更新。)

3 个答案:

答案 0 :(得分:3)

在主类的构造函数中创建对象'Configs'。执行此操作时,请为Config对象提供对主类的引用。现在Configs可以访问主类的值。

答案 1 :(得分:1)

您需要将游戏类的引用传递给Configs类。在Configs的类构造函数中,将私有成员变量设置为游戏类的实例。从那里你可以操纵游戏。见下文:

游戏类

public class Game1 : Game
{
    Configs configs; 

    GraphicsDeviceManager _graphics;
    SpriteBatch _spriteBatch;

    public Game1()
    {
        _graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        // Pass THIS game instance to the Configs class constructor.
        configs = new Configs(this);
        base.Initialize();
    }

    protected override void LoadContent()
    {
        _spriteBatch = new SpriteBatch(GraphicsDevice);
    }

    protected override void UnloadContent()
    {
    }

    protected override void Update(GameTime gameTime)
    {
        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        base.Draw(gameTime);
    }
}

配置班级

public class Configs
{
    // Reference to the main game class.
    private Game _game;

    public Configs(Game game)
    {
       // Store the game reference to a local variable.
        _game = game;
    }

    public void SetMouseVisible()
    {
        // This is a reference to you main game class that was 
        // passed to the Configs class constructor.
        _game.IsMouseVisible = true;
    }
}

这基本上是其他人所说的。但是,在没有看到某些代码的情况下,您似乎很难理解这些概念。因此,我提供了它。

希望有所帮助。

答案 2 :(得分:0)

有三件事,它们都与你对@Patashu答案的评论有关:

首先,如果要将Game对象传递给构造函数,则不需要将其设置为ref类型参数,因为它会通过引用自动传递(由于是对象)。

其次,您的GameComponent子类需要在其默认构造函数中引用Game对象的原因是它已经内置了Game的引用。在Configs课程中,请致电this.Game这是主Game个实例。

第三,如果你的构造函数已经收到了一个对象的一个​​参数,那么它不需要同一个对象的同一个实例的另一个参数。

Read the documentation.这很有用。

相关问题