- Home /
Question by
justkedin · Jul 19, 2014 at 11:36 AM ·
coroutinereturnreturn value
Return value from coroutine
I have this non-monobehaviour script where I have a function that needed to have a delay before it does what it needs to do. But since this cannot be done, I created a Monobehaviour script to do the waitforseconds thing for my original script. And it went like this:
void Example(string message){
StartCoroutine(sendMessage(message));
}
IEnumerator sendMessage(string message){
yield return new WaitForSeconds(1);
//.........
//Send message algorithm
//Need to return bool(if sending was successful)
}
I needed to have the bool value in my non-monobehaviour script and I need it only after the sending is done.
So my question is, can a coroutine return a value? If not, is there any alternate way I can do this? Thanks a lot!
Comment
Answer by jheiling · Jul 19, 2014 at 11:59 AM
No, you can't. But you can use a callback
IEnumerator sendMessage(string message, Func<bool> onSuccess){
yield return new WaitForSeconds(1);
//.........
//Send message algorithm
onSuccess(result);
}
I haven't tested this of course, but something like this? (similar to jheiling's answer)
void Example(string message){
StartCoroutine(send$$anonymous$$essage(message, onSuccess, onFail));
}
void onSuccess()
{
}
void onFail()
{
}
IEnumerator send$$anonymous$$essage(string message, Action successCallback, Action failCallback){
yield return new WaitForSeconds(1);
//.........
//Send message algorithm
if(result)
successCallback();
else
failCallback();
}
It doesn't. He probably mean Action ins$$anonymous$$d of Func