Reputation: 15
I need a Coroutine to stop until one of the conditions is met. Particularly, I need coroutine to wait until user presses one of two keys (R or T), or when my "timer" goes off, and then I need coroutine to continue. Timer is a float variable which I decrease by Time.deltaTime in Update method. Basically, I need to put a couple of conditions in yield return new WaitUntil() , if it is possible. I know how to write conditions themselves, but I don't know what to use to stop the coroutine until one of multiple conditions are met.
So is there a way to do something like that?
Upvotes: 0
Views: 175
Reputation: 17858
I think you are over complicating it.. so. This is not a whato todo but a working example of how to use multiple conditions.
I have not compiled this code so typos galor I expect..
bool inputreceived=false;
IEnumerator test()
{
inputreceived = false;
yield return new WaitUntil(inputreceived);
dostuff();
}
void Start()
{
StartCoroutine("test"); // or use a better non string manner
}
void Update()
{
if (Input.GetKeyDown(Keycode.R) || Input.GetKeyDown(Keycode.T)) inputreceived=true;
}
Upvotes: -1
Reputation: 90679
You could do
IEnumerator ConditionCoroutine()
{
print("Before condition");
var hasPressedR = false;
var hasPressedT = false;
float timer = XY;
while(true)
{
timer -= Time.deltaTime;
if(Input.GetKeyDown(KeyCode.R)) hasPressedR = true;
if(Input.GetKeyDown(KeyCode.T)) hasPressedT = true;
if(timer <= 0 && hasPressedR && hasPressedT)
{
break;
}
yield return null;
}
print("After condition");
}
and avoid having a lot of fields in your class itself or depending on Update
.
Upvotes: 0
Reputation: 28
IEnumerator ConditionCoroutine()
{
print("Before condition");
yield return new WaitUntil(() =>
(Input.GetKeyDown(KeyCode.R) || Input.GetKeyDown(KeyCode.T) || IsTimerEnd)
);
print("After condition");
}
Upvotes: -1