- Home /
When using yield and WWW-class the function wont run
Having a bit of trouble with contacting something on a server. Lets say I have a script like this:
static function postSomething () {
Debug.Log("Hello World");
var thePost : WWW = new WWW ("http://server.com/?foo=bar");
yield thePost; //Yield makes the function never shoot off
if(thePost.error) {
Debug.Log("Error posting: " + thePost.error);
}
}
Now, if I remove the yield the function shoots off and prints "Hello World", but nothing actually gets posted from Unity onto the server. If I directly post it inside a browser, the php-script takes care of it so there's nothing wrong on that end. I experience the same issue with WWWForm. So my question is, what am I missing?
Answer by Steven-Walker · Oct 06, 2011 at 12:24 AM
Your problem is that the function is static. You cannot use yield in a static method. Instead, you'll need to create a script that can be instanced. I handle this in my code by using the singleton pattern. You can build a class with static access methods, but they delegate to a single instance of the object that is setup just once and a reference to it is stored.
class MyExample extends Monobehaviour {
static public var Instance : MyExample;
function Init() {
if(!Instance) {
var g : GameObject = new GameObject("MyExample");
Instance = g.AddComponent(typeof(MyExample)) as MyExample;
}
}
function OnDestroy() {
Instance = null;
}
static function postSomething() {
Init();
Instance._PostSomething();
}
function postSomething() {
Debug.Log("Hello World");
var thePost : WWW = new WWW ("http://server.com/?foo=bar");
yield thePost; //Yield makes the function never shoot off
if(thePost.error) {
Debug.Log("Error posting: " + thePost.error);
}
}
}
I noticed a mistake in my code example above... the second postSomething routine should be named _PostSomething.
Roger that, nothing that Unity wouldn't have screamed about. :-) The big issue for me was that Unity was all nice and quiet, a "Did you just run a yield inside static function, have you learned nothing?" would have been nice!
So the idea is that you are calling init() for all the static functions in your class?
Your answer
Follow this Question
Related Questions
yield www javascript 1 Answer
Yielding with WWW in Editor 9 Answers
Unity 5.6.7 - UnityWebRequest SSL/HTTPs 2 Answers
yield on www download or check www.isDone (in an update)? 1 Answer