Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Is using GetComponent slow?

Discussion in 'Scripting' started by Rollo357, Dec 22, 2009.

  1. Rollo357

    Rollo357

    Joined:
    Nov 26, 2009
    Posts:
    49
    Hi,

    I'm using GetComponent to access variables in another script. I read somewhere that it was "relatively" slow. Is there a better way?

    Just one more thing, FPSWalker seems to lag my program too. Not when I'm moving forward, just when I want to rotate left or right.

    Thanks,

    Chris
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    If you're using GetComponent a lot (like every frame), cache the component. Otherwise don't worry about it. Describe "lag", because there's nothing in the FPSWalker script that's slow.

    --Eric
     
  3. HiggyB

    HiggyB

    Unity Product Evangelist

    Joined:
    Dec 8, 2006
    Posts:
    6,183
    The trick here is to avoid calling it repeatedly, call it once and store the reference obtained in a variable then use that variable later when needed. Here are two simplistic examples:

    Code (csharp):
    1. // Bad
    2. function Update () {
    3.     var yourScript : ExampleScript = GetComponent (ExampleScript);
    4.     yourScript.foo = 5;
    5. }
    Code (csharp):
    1. // Good
    2. var yourScript : ExampleScript;
    3.  
    4. function Start () {
    5.   yourScript = GetComponent (ExampleScript);
    6. }
    7.  
    8. function Update () {
    9.   yourScript.foo = 5;
    10. }

    Again, the above are extremely simplistic but designed to prove a point. If you know you're going to need to access a component repeatedly then get a reference to it one time, then use that stored reference when necessary. This avoids the need to call GetComponent() repeatedly which can in fact be a performance drain if done in excess. Please note that this is a general strategy you should keep in mind across the board, any "finder" functions like that have to do some amount of work to look-up/find the item in question and that takes time (even if only tiny slices). But lots of tiny slices can add up, so cache references!
     
  4. Rollo357

    Rollo357

    Joined:
    Nov 26, 2009
    Posts:
    49
    Edit: Nevermind, thanks for your help guys :)

    Chris.