Search Unity

  1. All Pro and Enterprise subscribers: find helpful & inspiring creative, tech, and business know-how in the new Unity Success Hub. Sign in to stay up to date.
    Dismiss Notice
  2. Dismiss Notice

Order of execution in UnityEvent.Invoke().

Discussion in 'Scripting' started by m_szadko, Aug 10, 2018.

  1. m_szadko


    Jul 11, 2018
    I know that there was similar threads but I'd like to get some official piece of documentation.

    In those threads :

    we can read that "...So internally this uses a delegate where call order is not defined..."

    but I've found this
    and there is a sentence "...When allMethodsDelegate is invoked, all three methods are called in order...".
    In addition this method
    suggest that delegates are called in order of the occurrence in the invocation list.

    So is there any official info about order invoking methods on UnityEvent?
    And what about C# delegates? Am I missunderstanding something from the docs or its just really common mistake that delegates are invoking in random order?

    If you can post some official writings about those topics I would really appreciate it.
  2. lordofduct


    Oct 3, 2011
    C# delegates are executed in the order they are added. Per their documentation.

    UnityEvent is not necessarily a delegate (though it is defined to be implemented by utilizing a delegate at some point internally).

    It's order is undefined not because of the delegate. But because there is no guarantee of the order in which the delegate is built.

    There's 2 common reasons something like this is left undefined.

    1) the designer is lazy and didn't define it (a total possibility if you've looked through Unity's documentation)

    2) the designer explicitly leaves it undefined (usually they describe it as undefined) because they want to allow themselves the ability to change the ordering in the future if there is ever a need to change it to resolve issues like bugs, speed issues, or any other sort of refactoring that may occur.

    This is similar to Components on a GameObject. Just because you see them in some order in the inspector, Unity does not define that order. At runtime the order in which the components have Awake/Start/Update called, how they're returned by GetComponents, and all that is undefined. Just in case they ever have to change it for whatever reason.

    Since UnityEvent explicitly say the call order is not defined we have a case 2 situation.

    What they mean is that "do not rely on the call order as it could change at any time".

    I've also found that in cases like this (such as the components), the order changes between editor and builds.
    Julian_Nementic likes this.