Reputation: 13610
I'm trying to make my GetStringFromServer method a bit more abstract, as I don't want to create the same method for all the different calls i make to the server, the result is always the same; a json string anyways.
public delegate void GoogleServerResponse(string result);
public static event GoogleServerResponse OnGoogleServerResponse;
void Start () {
print ("going to google...");
StartCoroutine( GetStringFromServer("http://google.com", OnGoogleServerResponse) );
}
IEnumerator GetStringFromServer(string url, Event e) {
WWW www = new WWW(url);
yield return www;
if( e != null )
e (www.text);
}
I imagine this could fire the the passed in event, with the URL, making me able to listen to the event, and having several defined event for the different calls to my webserver (not google ofc, but typically "/getplayer", "/createnewgame" and so on).
Upvotes: 0
Views: 38
Reputation: 73442
The fact that you can't pass events around are applicable only when you're trying to pass the event of another class(Outside of the class).
If you're trying to pass the events around from the class which defines the events nobody stops you in doing that.
For instance the following works for me.
public delegate void GoogleServerResponse(string result);
public class PassEvent
{
public static event GoogleServerResponse OnGoogleServerResponse;
private void Start()
{
print("going to google...");
StartCoroutine(GetStringFromServer("http://google.com", OnGoogleServerResponse));
}
private void print(string p)
{
}
private void StartCoroutine(IEnumerator enumerator)
{
}
private IEnumerator GetStringFromServer(string url, GoogleServerResponse myEvent)
{
Uri www = new Uri(url);
yield return www;
if (myEvent != null)
{
myEvent(www.text);
}
}
}
Side note: Avoid naming the events with "On" prefix, helper methods which invokes the events should be named with [On]EventName
naming convention.
Upvotes: 1
Reputation: 22038
You cannot pass an Event
, you should try a (proxy/wrapper) Action
instead.
IEnumerator GetStringFromServer(string url, Action<string> e) {
WWW www = new WWW(url);
yield return www;
if( e != null )
e (www.text);
}
And call it like this:
StartCoroutine( GetStringFromServer("http://google.com", (param) => {
if(OnGoogleServerResponse != null)
OnGoogleServerResponse(param);
}));
Upvotes: 0