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

SendMessage vs direct function calls

Discussion in 'Scripting' started by limey, Apr 11, 2012.

?

Which do you prefer?

  1. SendMessage

    13.2%
  2. Direct function calls

    86.8%
  1. limey

    limey

    Joined:
    Dec 1, 2011
    Posts:
    6
    In my company, I am currently working on some utilities for Unity, which we are planning on releasing. One of these utilities requires a lot of user-initiated calls between classes. This has led to a design question; which do people prefer using, the SendMessage functions within components, or direct function calls?

    Personally, I always prefer directly calling functions. It looks neater in code, and you always know that the right thing is picking up the message, but I'm interested in other people's views on this.
     
  2. MADmarine

    MADmarine

    Joined:
    Aug 31, 2010
    Posts:
    627
    If you're interested in performance and reliability at all, you'll use direct function calls. Relying on reflection for menial tasks is just plain lazy. Only use SendMessage if you have to.
     
  3. kantaki

    kantaki

    Joined:
    May 15, 2011
    Posts:
    254
    Can you give me an example where i have to use Sendmessage ? Because i never really used it
     
  4. Tseng

    Tseng

    Joined:
    Nov 29, 2010
    Posts:
    1,217
    Maybe events may be suitable? Or virtual methods which can be overriden by the user (which is basically using direct calls)


    Rarely. Usually in bad designed (or programming beginner's) code, where you are not certain that the method exists or not.

    Usually interfaces/abstract classes and events make the use of SendMessage obsolete. Imho it's mostly a shortcut for UnityScript, which lacks events and interfaces/abstract classes are not used that much (dunno if its even possible)
     
  5. MADmarine

    MADmarine

    Joined:
    Aug 31, 2010
    Posts:
    627
    For the purposes mentioned here, in all honesty I can't really think of a situation where you'd have to use it. There's usually always a better solution, if you can't access something directly, there's always event based approaches like Tseng said.

    When it comes to advanced things like making an in game console for your application, SendMessage becomes useful. Any time where you'd actually take the time and trouble to implement reflection in your application would probably be a good time.
     
    Last edited: Apr 13, 2012