我正在开发一款游戏。我希望每个游戏实体都有自己的Damage()
功能。被叫时,他们会计算出他们想要做多少伤害:
public class CombatantGameModel : GameObjectModel
{
public int Health { get; set; }
/// <summary>
/// If the attack hits, how much damage does it do?
/// </summary>
/// <param name="randomSample">A random value from [0 .. 1]. Use to introduce randomness in the attack's damage.</param>
/// <returns>The amount of damage the attack does</returns>
public delegate int Damage(float randomSample);
public CombatantGameModel(GameObjectController controller) : base(controller) {}
}
public class CombatantGameObject : GameObjectController
{
private new readonly CombatantGameModel model;
public new virtual CombatantGameModel Model
{
get { return model; }
}
public CombatantGameObject()
{
model = new CombatantGameModel(this);
}
}
但是,当我尝试调用该方法时,出现编译错误:
/// <summary>
/// Calculates the results of an attack, and directly updates the GameObjects involved.
/// </summary>
/// <param name="attacker">The aggressor GameObject</param>
/// <param name="victim">The GameObject under assault</param>
public void ComputeAttackUpdate(CombatantGameObject attacker, CombatantGameObject victim)
{
if (worldQuery.IsColliding(attacker, victim, false))
{
victim.Model.Health -= attacker.Model.Damage((float) rand.NextDouble()); // error here
Debug.WriteLine(String.Format("{0} hits {1} for {2} damage", attacker, victim, attackTraits.Damage));
}
}
错误是:
'伤害':无法引用某种类型 通过表达;尝试 'HWAlphaRelease.GameObject.CombatantGameModel.Damage' 代替
我做错了什么?
答案 0 :(得分:2)
您需要先将该函数与该委托相关联,然后才能调用它。
这里你不需要代理 - 使用你拥有的代码,你最好将你的Damage函数作为接口的实现,或者在基础{{1中将它声明为抽象(或虚拟)类,以便派生类可以(或必须)覆盖它。
答案 1 :(得分:1)
您实际上声明了一个名为Damage的嵌套委托 type ,而不是该类型的实例。可以把它想象为一个类和一个类的实例之间的区别。
要实际使用您的委托,您必须声明一个字段,属性或事件来保存它。
例如:
// note that the delegate can be declared either in a class or outside of it.
public delegate int Damage(float randomSample);
public class CombatantGameModel /* ... */
{
/* ... */
public Damage DamageCalculator { get; set; }
}