Hi everyone,
I’m writing a custom monobehaviour where I need to define in several fields some delays, and I want the level designer to have as much freedom as possible when playing with those parameters
in the real case scenario I have a monobehaviour that gets triggered for some reasons, then I have a customizable delay (frames, seconds, or a combinations of the two) before checking other conditions, and, if the conditions are met, I want to be able to specify again an extra delay after the condition checking for the final effect to take place.
I’ve discovered I should be subclassing from YieldInstruction to do that, but can’t find much info about this, nor examples.
So, here’s the code so far:
[System.Serializable]
public class WaitTimeEx : CustomYieldInstruction
{
public enum WaitModes {
NotZero,
Cumulative,
ConcurrentFirst,
ConcurrentLast
}
public int frames;
public float seconds;
public WaitModes waitMode;
protected float startTime;
protected int framesPassed;
public override bool keepWaiting
{
get {
switch (waitMode)
{
case WaitModes.Cumulative:
???
break;
case WaitModes.ConcurrentFirst:
framesPassed++;
return (Time.time - startTime < seconds && framesPassed < frames);
break;
case WaitModes.ConcurrentLast:
???
break;
default:
???
break;
}
}
}
public WaitTimeEx(int frames, float seconds, WaitModes waitMode = WaitModes.NotZero)
{
this.frames = frames;
this.seconds = seconds;
this.waitMode = waitMode;
Reset();
}
protected void Reset()
{
startTime = Time.time;
framesPassed = 0;
}
public Wait()
{
Reset();
}
}
// Declaration in class:
public WaitModeEx delayBeforeConditionCheck;
public Condition condition;
public WaitModeEx delayAfterConditionCheck;
// Usage:
yield return delayBeforeConditionCheck();
if (condition.IsTrue())
{
yield return delayAfterConditionCheck;
<do some stuff>
}
I’ve never written a similar code, so I’m a bit lost. I’m not sure the WaitModeEx fields are going to show up in the inspector, or if I’m going to have to declare a similare WaitInfo class to save the 3 params to pass to the WaitTimeEx function.
Could someone please help me in filling the gaps? I know I should return true to delay the function and false to exit from it, but that’s all, I’m a bit unsure, yet I believe it’s possible to build such a class.
for reference:
https://blogs.unity3d.com/2015/12/01/custom-coroutines/
http://chriskugler.com/2016/01/25/unity-customyieldinstruction/
I’ll keep experimenting but I’m not sure that’s the proper way to do it.