c# - 从另一个类访问实例化对象 - C#

标签 c# object xna-4.0 instantiation

我有一个 Player class、NPC class、BattleManager class 和 Game class

玩家类别存储/获取/设置玩家统计数据,例如健康、耐力、等级、经验。 NPC 类似,但针对的是 NPC。 Game class 实例化 Player class 和 NPC class。游戏玻璃有两种游戏状态,战斗和非战斗。

当玩家处于战斗状态时,GameState进入战斗状态,当战斗结束时,切换为非战斗状态。

我想做的是让 BattleManager class 管理 NPC 和玩家之间的战斗,但是,由于玩家和 NPC 对象是在 Game 类中实例化的,我需要知道如何传递该对象或从 BattleManager 访问它,而无需实例化新对象。

任何人都可以建议其工作原理的一般流程吗?我知道这是错误的,但是有没有办法做类似 Game.Player.Health -= Damage; 的事情?例如,在player中classpublicint Health get/set,当Player类实例化时,如何编辑其他类的健康状况在游戏课上?有没有办法传递 Player object 或者只是从其他类访问 Game 类中创建的实例化对象?

最佳答案

我同意第一条评论,即探索一些设计模式是值得的。

如果您想要一个快速而肮脏的答案,那么:

修改您的 Player 和 NPC 类,以在构造函数中获取 Game 实例(另一种模式是让 Game 对象成为全局单例...另一种需要探索的模式)。

此处使用更简单的方法:

public class Game
{
    public Player PlayerProperty {get; set;}
    public NPC NPCProperty {get; set;}

    public foo() //some method to instantiate Player and NPC
    {
       PlayerProperty = new Player(this); //hand in the current game instance
       NPCProperty = new NPC(this);  //hand in the current game instance
    }
}

然后,在你的 Player 和 NPC 类中...

//Only example for Player class here... NPC would be exact same implementation
public class Player
{

    public Game CurrentGame {get; set;}

    public Player(Game gameInstance)
    {
        CurrentGame = gameInstance;
    }

    //then anywhere else in your Player and NPC classes...
    public bar() //some method in your Player and NPC classes...
    {
        var pointerToNPCFromGame = this.CurrentGame.NPCProperty;
        //here you can access the game and NPC from the Player class
        //would be the exact same for NPC to access Player class
    }
}

这是我可怜疲惫的大脑打出来的,所以请原谅任何错误。希望这会有所帮助。

关于c# - 从另一个类访问实例化对象 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11680349/

相关文章:

c#(更具体地说是 xna)如何通过 http 请求 xml 文件?不需要支持 xbox

c# - PO 文件本地化无法按预期用于数据注释

arrays - Swift 库中的数组问题 - Realm 2.4.1

php - 将类 stdClass 的对象转换为 JSON 对象

c# - AI 敌人在追逐玩家时会聚在一起

c# - 从datagridview插入数据到数据库

java - 什么是 Java 中的三元组?

xna-4.0 - 如何在 XNA 4.0 中取消设置纹理数据

c# - 如何从Texture2D XNA c#获取颜色和坐标(x,y)?

c# - 在 C# 列表中如何选择所有列+几个自定义列,以便在每一行中所有列都是扁平的(不是嵌套的)?