在 Unity 中创建能力对象



选择字符时,我目前有一个基类

abstract class CharacterClass
{
public abstract void AbilityOne();
public abstract void AbilityTwo();
}

我的角色来源于这个类

class Warrior : CharacterClass
{
public override void AbilityOne()
{
// implement ability one here
}
public override void AbilityTwo()
{
// implement ability two here
}
}

最后,我使用此代码选择战士

CharacterClass selectedClass = new Warrior(); // start the game as a Warrior

所以这种方式工作得很好。但是当涉及到冷却时间等时。我想保持干净的代码,所以我考虑创建一个Ability类。

我的抽象父类

abstract class CharacterClass
{
public Ability AbilityOne { get; set; }
public Ability AbilityTwo { get; set; }
}

勇士级

class Warrior : CharacterClass
{
public Warrior()
{
// Set the new Abilities
AbilityOne = new Ability(3, Smash()); // pass in the method as a parameter ??
AbilityTwo = new Ability(7, Shieldblock());
}
private void Smash()
{
// Ability 1
}
private void ShieldBlock()
{
// Ability 2
}
}

还有我的技能课

class Ability
{
public Ability(int cooldown, [the ability method here])
{
CoolDown = cooldown;
TheAbility = ? the ability parameter ?
}
public int CoolDown { get; set; }
public void TheAbility(){}
}

因此,战士将传递他的两个技能并创建两个能力对象。在游戏中我可以写

CharacterClass selectedClass = new Warrior();
selectedClass.AbilityOne();

这将导致冷却时间为 3 秒的粉碎。这是否可以实现..不知何故。。?

由于AbilityOne返回一个Ability对象,因此在Ability类中创建处理能力可能具有的不同逻辑的基础设施是有意义的,例如,以某种Update()方法在冷却计时器上运行时钟,使用该能力等。

因此,调用能力的代码如下所示:

selectedClass.AbilityOne.Trigger();

将能力方法存储为能力类中的System.Action也是有意义的。

class Ability
{
public Ability(int cooldown, System.Action _abilityMethod)
{
CoolDown = cooldown;
abilityMethod = _abilityMethod;
}
public int CoolDown { get; set; }
public void Trigger()
{
if( abilityMethod != null )
{
abilityMethod();
}
}
private System.Action abilityMethod;
}

你应该能够做这样的事情:

class Ability
{
public Ability(int cooldown, Action ab)
{
CoolDown = cooldown;
TheAbility = ab;
}
public int CoolDown { get; set; }
public Action TheAbility;
}

class Warrior : CharacterClass
{
public Warrior()
{
// Set the new Abilities
AbilityOne = new Ability(3, Smash);
AbilityTwo = new Ability(7, ShieldBlock);
AbilityOne.TheAbility(); // Will run Smash() method
}
private void Smash()
{
// Ability 1
}
private void ShieldBlock()
{
// Ability 2
}
}

最新更新