Search Unity

Question Mobile Cache or GetComponent ?

Discussion in 'Scripting' started by MX-Pain, Sep 26, 2022.

  1. MX-Pain

    MX-Pain

    Joined:
    Sep 27, 2020
    Posts:
    49
    Hello there,
    I have been watching a few tutorials and they have always mention that we should cache components when you are working on mobile. Instead of doing GetComponent.
    upload_2022-9-26_11-57-24.png

    I mean, instead of drag & drop . Do it via code.
    Code (CSharp):
    1.     void Awake()
    2.     {
    3.         health = GetComponent<HealthManager>();
    4.         collider = GetComponent<Collider2D>();
    5.     }
    Is this entirely true ? For this specific case, I'm using an Object Pooler so every object I'm disabling and re-enabling again. Is not caching all the time. Even tho, Awake is just calling once.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    Most of what they mean is to save them in variables as you are doing instead of calling GetComponent every time you use them. Between the two examples you shared here, there won't be any noticeable performance difference. What would be bad is doing something like this for example:
    Code (CSharp):
    1. void Update() {
    2.   if (GetComponent<HealthManager>().hp < 0) {
    3.     Die();
    4.   }
    5. }
     
    MX-Pain likes this.
  3. MX-Pain

    MX-Pain

    Joined:
    Sep 27, 2020
    Posts:
    49
    Oh okay okay.
    I believe that's what they mean then. That's example you wrote is a much better of a bad approach of cahing component every frame.
    Thank you tho. I'm looking to also not have a big hierarchy and filling all the vars accordingly.