A few days ago I started a new project, a MOBA like test, and it is been going well for the most part. Currently I am having difficulties importing slowness effect or buff/debuff system in to the game. The exact problem is with the timer I need to change the speed value of the character but I can not use ref/out parameters in coroutines. I tried some other things like using invoke or using functions but they just do not do what I want. All feedback is appreciated and thanks in advance
Here is the code:
Coroutine:
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;
}
Where I call the coroutine
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);
}
}
CodePudding user response:
You can't use ref
in IEnumerator, the Action<float>
solves the problem. This method is called 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);
}
The following lambda can execute your command after wait simply.
foreach(Collider c in colliders)
{
/// ...
player.ApplyDebuff(player.speed, 70, 5, debufValue => player.speed-=debufValue, orginalValue => player.speed = orginalValue);
///...
}
For using System
library as write using system
in top of code;