【问题标题】:How to use a public bool from one class in another class? c#如何在另一个类中使用一个类的公共布尔值? C#
【发布时间】:2016-03-11 04:57:06
【问题描述】:

我正在尝试在 Health 类中使用 Level 类中的布尔值,但我无法让它工作。我知道这可能真的很微不足道,但现在我被困住了..

这是类级别的 Uphealth 方法:

public bool UpHealth()
{
    SpriteGameObject healthpack = this.Find("uphealth") as SpriteGameObject;
    Player player = this.Find("player") as Player;
    if (healthpack.CollidesWith(player))
        return true;
    return false;
}

这是 Health 类中我想使用 bool Uphealth 的方法:

public override void Update(GameTime gameTime)
{
    base.Update(gameTime);
    Player player = GameWorld.Find("player") as Player;
    AnimatedGameObject rocket = GameWorld.Find("rocket") as AnimatedGameObject;

    foreach (GameObject obj in gameObjects)
    {
        SpriteGameObject h = obj as SpriteGameObject;
        if ( <---I DON'T KNOW WHAT TO TYPE HERE---> )
        {
            this.Add(h);
            return;
        }
    }
}

我希望它在 Uphealth 为 true 时执行 this.Add(h);

我需要做什么才能在 Health 类中使用 Uphealth?

【问题讨论】:

  • 你需要一个Level类的实例

标签: c# class xna boolean


【解决方案1】:

首先,创建“Level”类的实例。最好的方法可能是在类声明中(使其成为成员)。

Level level;

之后,只需确保它存在即可。

level = new Level(); // <------ I would probably put this in "LoadContent()"

最后,你可以这样使用它

if (level.UpHealth())
{
    // Do really cool stuff here
}  

希望能帮到你。

【讨论】:

  • 谢谢!但我还有一个问题:在关卡类的构造中,我给出了一个 levelindex 参数,所以现在我必须弄清楚
  • 如果您发布相应的代码,我也可以帮助您! :)
  • 那太好了!我应该添加一个新问题吗?因为如果在注释中放很多代码,就会很难阅读
  • 我已经发布了问题:)
猜你喜欢
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多