save
1
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);
}
}
}