Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

BroadcastMessage() Internals and Performance

Discussion in 'Scripting' started by SGDavid, Mar 17, 2010.

  1. SGDavid

    SGDavid

    Joined:
    Mar 17, 2010
    Posts:
    12
    We've used game engines in the past that have event handling systems where you basically say "X Happened" and any class in the game that was listening for that event would receive it and do something.

    I am considering parent everything in the game to a single GameObject, then simply calling BroadcastMessage() on it to achieve the above-mentioned functionality. I know this works, but I'm concerned about performance.

    How does BroadcastMessage() work internally and how is the performance? Does it only keep a list of classes that actually implement the message or does it iterate over EVERYTHING? Something else?

    Thanks!
     
  2. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    Hi, welcome to the forum!

    I'm pretty sure BroadcastMessage just iterates through all possible target objects (the object hierarchy is not fixed and any number of functions could potentially be called - caching would be very difficult). Moreover, the process of sending a message is probably about 10x slower than a function call, as investigated in this thread. The idea you have suggested is probably workable for a reasonable number of objects if you are just broadcasting occasional state change messages. However, you wouldn't want to use something like this on every frame update.
     
  3. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    What I would recommend in such a case is that you implement a handling structure in the style of the observer pattern.

    I know that such a system already exists (a message system where you send messages and the main handling class dispatches them to all listener for that message type). I think it was done by flashbang studios as so many other small yet usefull things :)
     
  4. SGDavid

    SGDavid

    Joined:
    Mar 17, 2010
    Posts:
    12
    Thanks for the info guys!

    I think I'll probably end up writing an event handling system (again!) as I described that leverages pointers just to make sure it will be fast. It won't be called every frame, but we will likely using it several times a second.