繁体   English   中英

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

[英]In XNA, how do I modify something in the main game class from another class?

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

我知道我可以在Configs类中创建一个bool值,然后按一下该键,该值将更改,然后在主Game类更新时,将IsMouseVisible的值设置为Configs类的值,但事实是,我可能想创建多个不同的值(不仅仅是IsMouseVisible ),可以在另一个类的主Game类中设置这些值。

我的问题是,我该如何在另一个主要课程的Game类别中设置一些内容? (无需为我希望可访问的每个值创建多个更新。)

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

您将需要将游戏类的引用传递给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;
    }
}

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

希望能有所帮助。

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

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

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

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

阅读文档。 很有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM