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

How often should I "GetComponent" ?

Discussion in 'Scripting' started by vistriter, Feb 8, 2017.

  1. vistriter

    vistriter

    Joined:
    Jan 22, 2017
    Posts:
    91
    I create base canvas. It's have template for information. After I click "Info" button. It's "GetComponent" to change text in canvas.

    I am not sure it's have performance.

     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,937
    One/few clicks wont matter, would be problem if you call it constantly inside a loop or so.

    You can still cache the result if you want,
    Code (CSharp):
    1. if (clicked..)
    2. {
    3. if (txtReference==null) txtReference=GetComponent<Text>(); // cache it if not yet
    4.   txtReference.text = "Nice!";
    5. ..
    6. }
    7.  
     
  3. vistriter

    vistriter

    Joined:
    Jan 22, 2017
    Posts:
    91
    Thanks You! I want to ask you. In mobile games. I wonders it's have many scenes or many canvas ??? Example Shop UI.
     
  4. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,184
    It should be pretty much the same. Unless you're running out of memory, you should keep things like the shop loaded and deactivated, so the player doesn't have to wait for them to get instantiated.

    For canvases, there's some clever things here about optimization.