When one should use events in Unity and how they impact performance?

let's say that inside an OnGUI() script we want to call a method from another script to handle a particular situation. From a prestational point of view, what's the difference between these 3 approaches?

1.

    public class SomeClass : MonoBehaviour{

...

void OnGUI(){
if(something)
otherClass.heavyWorkMethod();
...
}
}


2.

public class SomeClassCoroutine : MonoBehavior{

...

void OnGUI(){
if(something)
StartCoroutine("someClassCoroutine");
...
}

IEnumerator someClassCoroutine(){
otherClass.heavyWorkMethod();
...
}
}


3.

public class SomeClassEvent : MonoBehavior{
public delegate void SomeAction();
public static event SomeAction OnEvent;
...

void OnGUI(){
if(something)
OnEvent();
}
}


Where in the third case, the heavyWorkMethod in OtherClass gets called when the event OnEvent is fired.

(1) is just a normal method call.

(2) is a Unity Coroutine. You should only use it when you need the special abilities that coroutines grant you (basically, when you need the execution of a single method to last multiple frames)

(3) is normal C# event. You can read about events in any book or tutorial on C#, but without getting into too much detail: they're used to signal that some event has occurred. This allows the users of your class to decide which events they care to handle, and which they don't. It's also a way to call methods higher up in the call-hierarchy.

(Note that it's very unusual to have a static-event. In every case I can think of that you'd use a static event, using a service would be better design).

There is a fourth option you missed: Unity Messages. A message is similar to an event that all other Components attached to that GameObject are automatically subscribed to. This allows your component to publish an event without other components having to explicitly subscribe to it. Functions like Start(), Awake(), OnGui etc. are all messages.

• Thanks for the answer. From a prestational point of view, though, when one has to deal with blocking operations is there a sensible difference between coroutines and events? What I mean, looking at the example above, is that: are both effective ways of dealing with blocking operations?
– zhed
Feb 15 '14 at 13:11