Search Unity

Auto attach components via attributes

Discussion in 'Assets and Asset Store' started by Nrjwolf, Jul 9, 2020.

  1. Nrjwolf

    Nrjwolf

    Joined:
    Mar 2, 2014
    Posts:
    4
    Hi there,

    I created attributes, which are auto attach components to your fields

    Github : https://github.com/Nrjwolf/unity-auto-attach-component-attributes

    About
    Once I was faced with the problem of null checking in unity. You can read about this here https://blogs.unity3d.com/ru/2014/05/16/custom-operator-should-we-keep-it/

    In short, if you use something like

    Code (CSharp):
    1. private Transform m_CachedTransform
    2. public Transform transform
    3. {
    4.   get
    5.   {
    6.     if (m_CachedTransform == null)
    7.       m_CachedTransform = InternalGetTransform();
    8.     return m_CachedTransform;
    9.   }
    10. }
    You will have performance problem, because unity overrides ==, also you with this point, you should be carreful with ? operator.

    So, I started to think, how to attach components without caching it every time in Awake/Start functions.

    Example of using :

    Code (CSharp):
    1. [FindObjectOfType]
    2. [SerializeField] private Camera m_Camera;
    3. [GetComponent]
    4. [SerializeField] private Image m_Image;
    5. [GetComponentInChildren(true)] // include inactive
    6. [SerializeField] private Button m_Button;
    7.  
    8. [GetComponentInChildren("Buttons/Button1")] // Get the component from the children by path "Buttons/Button1" in hierarchy
    9. [SerializeField] private Button m_Button;
    10. [AddComponent] // Add component in editor and attach it to field
    11. [SerializeField] private SpringJoint2D m_SpringJoint2D;
    Also, you can easily turn it on/off, because attributes will not give you opportunity to use default drag&drop


    Enjoy!

    Telegram : https://t.me/nrjwolf_live
    Discord : https://discord.gg/jwPVsat
    Reddit : https://www.reddit.com/r/Nrjwolf/
    Twitter : https://twitter.com/nrjwolf
     
    DavidLe360 and natteo like this.
  2. kaiyum

    kaiyum

    Joined:
    Nov 25, 2012
    Posts:
    686
    Hi, I am considering using your library in our project. However, do you do anything in runtime, or all the work done to set the attributes live in the editor only? If you do anything in runtime, then,
    1. Do you use reflection? Linq?
    2. Where the runtime code lives at? Awake? Start?
     
  3. PaperPrototype

    PaperPrototype

    Joined:
    Jan 3, 2018
    Posts:
    7
    He does it in an Editor script