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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

What is your prefered way to communicate between components?

Discussion in 'Scripting' started by DamonJager, Jun 29, 2016.

  1. DamonJager

    DamonJager

    Joined:
    Jul 16, 2015
    Posts:
    56
    GetComponent? messages? a centralized game manager?
     
  2. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    I like GetComponent<T>() then holding onto the reference if possible.
     
  3. listener

    listener

    Joined:
    Apr 2, 2012
    Posts:
    179
    This really depends on your architecture. One of good ways is using events since it allows invoking events and subscribing to events from multiple locations anonymously.
     
  4. MikeTeavee

    MikeTeavee

    Joined:
    May 22, 2015
    Posts:
    194
    Most of the time I use a centralized class attached to an empty GameObject. Sometimes I do what @Garth Smith does and use a reference set by GetComponent in Start().
    Once in a blue moon, or dealing with GUIs I use SendMessage().
    I very rarely use events, I don't like them because the code is messy.

    ...speaking of clean code, I've heard of assets on the Unity store that will handle communication between objects with very minimalistic code. I may look into this for my next project.
     
  5. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Whatever works for the situation. GetComponent, singleton, static references, inspector references, dynamic loading, manager classes, GameObject.Find, ExecuteEvents... And so on.

    I really don't have a favourite. I just use whatever structure is relevant to the game I'm building.
     
  6. DamonJager

    DamonJager

    Joined:
    Jul 16, 2015
    Posts:
    56
    I've never used messages, but if I want to decouple the code even more, I would use them. It feels and might be the "correct thing to do", but i find it ugly, messy, and difficult to debug.

    Of course it depends of context.