- Home /
Make a function that can return string or IEnumerator
Hello, I'd like to make a function which can for some arguments return string and for some arguments can pause execution for some time (yield return new WaitForSeconds(1f)). For example:
public IEnumerator Process(string s) {
if (s == "wait") yield return new WaitForSeconds(1f);
else return "hello";
}
Debug.Log(StartCoroutine(Process("wait"))); // pauses execution for a second
Debug.Log(tartCoroutine(Process("hi"))); // logs "hello" to console
Answer by Hellium · Dec 22, 2018 at 01:52 PM
This is not possible this way, a function in C# only returns one type. An alternative would be to use a Action
that will be called once the coroutine ended:
public IEnumerator Process(string input, System.Action<string> onMessageReceived )
{
output = null;
if (s == "wait")
{
yield return new WaitForSeconds(1f);
}
else
{
output = "hello";
}
if( onMessageReceived != null )
onMessageReceived( output ) ;
yield return null ; // Needed
}
StartCoroutine( Process("wait", output => Debug.Log( output ) ) );
StartCoroutine( Process("hi", output => Debug.Log( output ) ) );
Answer by toddisarockstar · Dec 22, 2018 at 01:58 PM
your question is a bit complicated because the IEnumerator and it's wait is happening in a different thread. Since you are using a "wait", if you did successfully get your main thread to wait for a return, You pry wouldn't want to freeze your entire game while the Coroutine is processing !!!
I'm not sure what you are trying to accomplish but maybe you could change a variable in your main script instead of using a return? then you would have to check back later with your main thread to see what it changed or use a get/set trigger on the variable you changing.
i would do this:
// wont freeze main thread
string xwow;
public string wow{get{return xwow;}set{
xwow = value;
print (xwow);}}
void Start () {
StartCoroutine(Process("wait")); // pauses execution for a second
}
public IEnumerator Process(string s) {
if (s == "wait") {
yield return new WaitForSeconds (1f);
wow = "ive waited";
} else {
wow = "hello";}}
anyways here is a link that explains a return if you want one: link text
No, coroutines do not run on a seperate thread. Coroutines implement cooperative multi tasking and is purely done on a single thread, the main thread. On the wiki you can find a custom CoroutineScheduler which does a similar thing as Unity's internal coroutine scheduler, but with slightly different yield values since the one implemented in Unity (WaitForSeconds, ...) store the required data internally.
Your answer
![](https://koobas.hobune.stream/wayback/20220612184420im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Backspace typewriter effect 1 Answer
StopCoroutine with IEnumerator not working 2 Answers
Coroutoutine doesnt work properly. 3 Answers
Use Coroutine when object rotates 2 Answers
Collection Change During Iteration 0 Answers