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

How to get a script Elegantly

Discussion in 'General Discussion' started by Ridiculously, Jul 20, 2020.

  1. Ridiculously

    Ridiculously

    Joined:
    Jul 13, 2020
    Posts:
    6
    plan A(when edit) public T t and then drag the target script (T) in hierarchy view
    plan B single instance public static T instance instance=this and use T.instance to get
    plan C static class
    plan D GetComponent<T>
    have any other plans (E F G...)?
    and which is the best way
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Different solutions for different situations. One is not strictly better than another.
     
  3. JohnnyA

    JohnnyA

    Joined:
    Apr 9, 2010
    Posts:
    5,039
    There's no wrong or right way, although some approaches might be better for specific scenarios. Some people will get quite attached to a specific pattern, and you should listen to their points particularly if you are new, but ultimately use the approach that works best for you and your team.

    Static instances are useful for manager classes where having a singleton makes sense. There are lots of different threads on best implementation, have a read.

    GetComponent in an initialisation method is useful when you expect (or force via RequireComponent) the component to be present.

    Assignment in the editor is useful when its not easy to determine from code which component should be used (for example if a complex character object had multiple animators but you only need to act on one of them).
     
    Last edited: Jul 20, 2020
    angrypenguin likes this.
  4. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    5,984
    What is elegance?
     
  5. Ridiculously

    Ridiculously

    Joined:
    Jul 13, 2020
    Posts:
    6
    low coupling and it makes your total code clearly
     
  6. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    5,984
    Well, that should already help you decide between those choices. Though it's usually a bit of a trade-off.