4
\$\begingroup\$

In my turn based game, I like to have a function similar to Unity's WaitForSeconds, WaitUntil that can be called within a IEnumerator that suspends the coroutine execution for the given amount of moves. I already have a public working UnityEvent (moveEvent) which I could listen to.

So I could call it from any IEnumerator like:

IEnumerator Example() { yield return new WaitForMoves(2); } 

I think I'd need a separate class like:

class WaitForMoves { int moves = 0; void Start() { Game.moveEvent.AddListener(OnMoveComplete); } void OnMoveComplete() { moves++; } // I'm not sure how to write this in a way that it waits // until this.moves === movesToWait public WaitForMoves(int movesToWait) { } } 
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

https://docs.unity3d.com/ScriptReference/CustomYieldInstruction.html

class WaitForMoves : CustomYieldInstruction { private int movesLeft; public WaitForMoves(int moves) { movesLeft = moves; Game.moveEvent.AddListener(OnMoveComplete); } void OnMoveComplete() { movesLeft—-; if (movesLeft <= 0) Game.moveEvent.RemoveListener(OnMoveComplete); } public override bool keepWaiting { get { return movesLeft > 0; } } } 

And to use it, just as you wanted:

yield return new WaitForMoves(2); 

If you have a global move counter in Game, then you wouldn’t need to have a listener at all:

class WaitForMoves : CustomYieldInstruction { private int targetMoves; public WaitForMoves(int moves) { targetMoves = moves + Game.moveCounter; } public override bool keepWaiting { get { return Game.moveCounter < targetMoves; } } } 
\$\endgroup\$
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.