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

GetComponent or simply word........?

Discussion in 'Scripting' started by U7Games, Jul 25, 2011.

  1. U7Games

    U7Games

    Joined:
    May 21, 2011
    Posts:
    943
    Hi, what is the difference between this two bits of codes ? :

    Code (csharp):
    1.  
    2. var myTransform : Transform = GameObject.Find("transformer").GetComponent(Transform);
    3.  
    and this one :


    Code (csharp):
    1.  
    2. var myTransform : Transform = GameObject.Find("transformer").transform;
    3.  
    by the way, both do exactly the same but technically don´t know the true difference...

    Greetings.
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    They are literally the exact same.

    .transform is the equivalent of GetComponent (Transform)
     
  3. U7Games

    U7Games

    Joined:
    May 21, 2011
    Posts:
    943
    so better to use transform alone to save time hehe thanks..
     
  4. Rafes

    Rafes

    Joined:
    Jun 2, 2011
    Posts:
    764
    And. most importantly, cache it to a variable so it only happens once.
     
  5. U7Games

    U7Games

    Joined:
    May 21, 2011
    Posts:
    943
    yes!, actually i have all the vars inside an Awake function is useful!
     
  6. bdev

    bdev

    Joined:
    Jan 4, 2011
    Posts:
    656
    If you can use the .transform property vs GetComponent(Transform). I can't really say that its faster to do it this way ( i think it probably is ) but in the worse case it would be as fast.
     
  7. U7Games

    U7Games

    Joined:
    May 21, 2011
    Posts:
    943
    i´m not a programmer, but i´m becoming a bit lazy with code, btw .. there are only few lines using transform component... and never used it on update functions, so i guess it might not be a problem !
     
  8. Rafes

    Rafes

    Joined:
    Jun 2, 2011
    Posts:
    764
    Right. Its all about context. Do it one and no big deal, do it 100 times per frame and you've got a problem.
     
  9. zine92

    zine92

    Joined:
    Nov 13, 2010
    Posts:
    1,347
    transform is already referenced to the transform component of the object i guess.
     
  10. Rafes

    Rafes

    Joined:
    Jun 2, 2011
    Posts:
    764
    You mean cached?
    I don't think it is. Unity recommends caching it.