Search Unity

Create custom System Event (like "OnClick" for example)

Discussion in 'Scripting' started by ackley14, Aug 31, 2015.

  1. ackley14

    ackley14

    Joined:
    Oct 31, 2014
    Posts:
    31
    I was wondering if it is possible to create a system-wide event or something to that nature, whereby ever active script containing that function would execute that function. similarly to how "onclick" for example works when you click on an object, all scripts on that object with the "onclick" function are fired.

    Right now im not looking for anything too specific, mostly just a "yes it is" or "no its not" and maybe a good place or thing to look up to get me headed in the right direction, asuming a feature like this is possible


    If you're curious as to why i'm looking for a feature like this, i'm working on an RPG sub-engine/library similar to how bethesda's creation kit works with papyrus (obviously on a much more dumbbed down scale) in an attempt to make various data lists, event triggers, and quest/dialogue creation more intuitive to program instead of kind of creating everything from scratch every time you need to implement it (or creating a "utilities" script for every project you work on with various useful functions)

    Thanks for any responses :3
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,528
    SendMessage calls a function on all scripts on a GameObject:
    http://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html

    SendMessageUpwards calls a function on all script of the parents of a GameObject:
    http://docs.unity3d.com/ScriptReference/GameObject.SendMessageUpwards.html


    And the one you're looking for probably...

    BroadcastMessage calls a function on all scripts on a GameObject and its children:
    http://docs.unity3d.com/ScriptReference/Component.BroadcastMessage.html

    None do ALL scripts in the entire scene. But if you just took all the root level GameObjects and called this, it'd work. Or if you structured your scene so that all GameObjects were the child of some root 'super parent', it would work.



    Of course though, I would argue that all the 'message' style systems can be a little slow due to its need to reflect the functions out of all the scripts. And instead registering for an even explicitly is a much more efficient way to do it.
     
    ackley14 likes this.
  3. ackley14

    ackley14

    Joined:
    Oct 31, 2014
    Posts:
    31
    thanks for that insightful info friend! i'll definitely to some speed testing, to see if it would be viable, i may come back to the event registering thing if things are taking too long

    again much thanks for the info :D
     
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    ExecuteEvents doesn't rely on the event system, so it's faster. It does require slightly more code.