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

时间:2012-07-27 01:36:51

标签: c# object xna-4.0 instantiation

我有一个玩家class,NPC class,BattleManager class和游戏class

玩家类存储/获取/设置玩家统计数据,如健康,耐力,等级,经验。 NPC类似,但适用于NPC。游戏class实例化玩家class和NPC class。游戏玻璃有两个游戏状态,战斗和非战斗。

当玩家在战斗中时,GameState会参加战斗,当战斗结束时,它会切换到非战斗状态。

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

任何人都可以建议一下这可能有用的一般流程吗?我知道这是错的,但有没有办法做Game.Player.Health -= damage;之类的事情?例如,在播放器classpublic int Health get/set,当在Game类中实例化Player类时,如何编辑其他类的运行状况?有没有办法传递Player object或只是从其他类访问Game类中创建的实例化对象?

2 个答案:

答案 0 :(得分:2)

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

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

修改你的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
    }
}

然后,在你的玩家和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
    }
}

从我疲惫不堪的大脑中输入这个,以免惹恼任何错误。希望这会有所帮助。

答案 1 :(得分:1)

我喜欢认为玩家和npcs是风景中的演员...所以我曾经用单例模式创建一个ActorManager类......

public interface IActor {
   Stats Stats {get;}
   Vector2 Position {get;}
   bool IsFighting {get;}
   bool IsActive {get;}  // Or whatever you need
}

public class ActorManager {

     public static readonly Instance = new ActorManager();

     ActorManager();

     List<IActor> _actors = new List<IActor>();

     public IEnumerable<IActor> Actors {get{ return _actors;}}

     public void Addactor(IActor actor) { ... }

     public IEnumerable<IActor> GetActorsNear(IActor actor, float Radius)
     {
         return _actors.Where( 
               secondary => actor != secondary 
               && Vector2.Distance(actor.Position, secondary.Position)<Radius);
     }

     // or whatever you want to do with actors

}

public abstract class Actor : IActor
{
   public Stats Stats {get; protected set;}
   public Vector2 Position {get;protected set;}
   public bool IsFighting {get;protected set;}
   public bool IsActive {get;protected set;} 

       public Actor() {
           ActorManager.Instance.Add(this);
       }

   public abstract void Controller();
}

public class Player : Actor { }  // Implements an input controller
public class Npc : Actor { } // Implements a cpu IA controller