- Home /
Waiting for and using output of a UnityEvent within coroutines
I would like to wait for a UnityEvent
in my coroutine AND use the output from said event in follow up execution of my code. Below is the draft code for my coroutine that waits until a card is selected by the player, triggered by an UnityEvent
, and uses said card to do something (discarding / destroying / copying the card).
public IEnumerator SelectionRequest()
{
Card card = null;
// Wait until user has selected appropriate cards
yield return WaitForSelection(returnValue =>
{
card = returnValue;
});
// Check if cards where selected
if (card == null)
{
// Selection is aborted by user, any following code should not be executed
yield break;
}
// Selection is performed correctly,
// Interact with the selected card in some way ...
}
The problem lies in the WaitForSelection
method that i have defined, which i would like to return the Card object that was passed as input argument to a UnityEvent
.
I've already set up a class to expose the UnityEvent
for easy editing in the editor, however i have not been able to wait for the event and use this variable from within the coroutine shown above.
[System.Serializable]
public class CardEvent : UnityEvent<Card[]>
{
}
The goal of this code is to be able to implement cards with more exotic effects in my card game. From cards that allow the player to discard other cards in their hand, to cards that allow players to destroy a card in hand and select a card that costs 2 more to add to their deck.
I'm open to other suggestions if you think coroutines for the card effects, and UnityEvent
s for selection are not the way to go for this functionality.
But how do i then set up the different effects of different cards? My idea was to have these different effects in unique coroutines where needed, and hook up to the event to get the card selected when this is needed. I don't see how i can do this without events or bloating all of the code...
Answer by Bunny83 · 6 days ago
You can use something similar to what I've implemented over here. Specifically a custom yield instruction that simply checks a boolean value that is set to true when the event has happened. My WaitForUIButtons class also takes care about registering and removing the callback from the button on click event. You could implement a similar class for wrapping around a UnityEvents (or multiple in case there are several choices).
Thanks, that does seem useful. But after some consideration i realized i could perhaps more easily do everything i need using unity events. Or at least it seems more easily scalable then your solution.