几天前,我开始了一个新项目,一个类似MOBA的测试,它在很大程度上进展顺利。目前我在导入慢速效果或buff/debuff系统到游戏中遇到了困难。确切的问题是定时器,我需要改变字符的速度值,但我不能在协程中使用ref/out参数。我尝试了一些其他的事情,如使用调用或使用函数,但他们只是不做我想要的。所有的反馈是赞赏和感谢提前
这是代码:
协同程序:
public IEnumerator ApplyDebuff(ref float stat, float percentage, float duration)
{
float originalValue = stat;
float timeStamp = Time.time;
while (Time.time < timeStamp + duration)
{
float debuffValue = percentage / 100 * originalValue;
stat -= debuffValue;
yield return null;
}
stat = originalValue;
}
调用协程
private void CheckForCollision()
{
Collider[] colliders = Physics.OverlapSphere(position, scale, layerMask);
foreach(Collider c in colliders)
{
c.TryGetComponent<PlayerController>(out PlayerController player);
player.ApplyDebuff(ref player.speed, 70, 5);
player.TakeDamage(50);
Destroy(gameObject);
}
}
你不能在IEnumerator中使用ref
,Action<float>
解决了这个问题。这个方法叫做Callback.
public IEnumerator ApplyDebuff(float stat, float percentage, float duration, Action<float> OnWhileAction, Action<float> AfterWaitAction)
{
float originalValue = stat;
float timeStamp = Time.time;
while (Time.time < timeStamp + duration)
{
float debufValue = percentage / 100 * originalValue;
OnWhileAction(debufValue);
yield return null;
}
AfterWaitAction(originalValue);
}
下面的lambda可以在等待之后执行命令。
foreach(Collider c in colliders)
{
/// ...
player.ApplyDebuff(player.speed, 70, 5, debufValue => player.speed-=debufValue, orginalValue => player.speed = orginalValue);
///...
}
使用System
库将using system
写入代码顶部;