A coroutine can only return type IEnumerator. I suspect that this is mainly due to the way it’s implemented, but anyway it would be complicated to return any useful value: the coroutine runs “in the background”, thus the return instruction may be executed a long time after the caller routine has finished.
EDITED: There are several possible ways to retrieve the result value from the coroutine, but you must keep in mind that the result may take an unpredictable time to get ready. You can use a flag to inform whether the result is ready, store the result in a member variable and read it when it’s valid:
private var result: int;
private var resultReady = false;
function RetrieveHunger(){
resultReady = false; // result isn't ready yet
var formHunger : WWWForm = new WWWForm();
formHunger.AddField("user", user);
var wHunger : WWW = new WWW("", formHunger);
yield wHunger;
// store the result:
if wHunger.error == null){
result = parseInt(wHunger.text);
} else {
result = -1;
}
resultReady = true; // result ready now
}
function Start(){
RetrieveHunger(); // start RetrieveHunger
}
function Update(){
if (resultReady){ // when result ready, display it:
guiText.text = "Result = " + result;
}
}
Another possibility is to chain to RetriveHunger, if the caller is a coroutine too:
private result: int;
function Start(){ // yield makes Start a coroutine
yield RetrieveHunger(); // call RetrieveHunger and wait for its completion
guiText.text = "Result = " + result; // display the result
}
Finally, you could simply call a callback function at the end of the coroutine. If you want to define which function to call when the coroutine finishes, pass it as a parameter:
function RetrieveHunger(callbackFunction: Function){
var formHunger : WWWForm = new WWWForm();
formHunger.AddField("user", user);
var wHunger : WWW = new WWW("", formHunger);
yield wHunger;
if (wHunger.error == null){
callbackFunction(parseInt(wHunger.text));
} else {
callbackFunction(-1);
}
}
The callback function itself could be something like this:
function GetResult(res: int){
guiText.text = "Hunger = " + res;
}
And it should be passed like below:
...
RetrieveHunger(GetResult);
...