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?
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);
}
}
}
Fantastic, many thanks for the heads up and example!
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!
Fantastic, many thanks for the heads up and example!
– saveI noticed a mistake in my code example above... the second postSomething routine should be named _PostSomething.
– Steven-WalkerRoger 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!
– saveAlso, when are you calling OnDestroy?
– inaSo the idea is that you are calling init() for all the static functions in your class?
– ina