3
\$\begingroup\$

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.

Thanks for your time. Looking forward to read your answers.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

(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.

\$\endgroup\$
1
  • \$\begingroup\$ 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? \$\endgroup\$
    – zhed
    Feb 15, 2014 at 13:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .