Author Topic: Is there a buiilt-in way to avoid GetComponent?  (Read 3431 times)

Disastercake

  • Jr. Member
  • **
  • Thank You
  • -Given: 0
  • -Receive: 1
  • Posts: 87
  • www.disastercake.com
    • View Profile
    • Disastercake
Is there a buiilt-in way to avoid GetComponent?
« on: July 13, 2012, 03:14:33 PM »
I want to try to avoid GetComponent as much as possible in my code.  What is the best way to grab something like a UILabel component to change it's text when it's created at runtime?
Creator of Soul Saga.
http://www.disastercake.com

JRoch

  • Full Member
  • ***
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 140
    • View Profile
Re: Is there a buiilt-in way to avoid GetComponent?
« Reply #1 on: July 13, 2012, 06:23:43 PM »
Create a local (private) variable of the type of the Component and only GetComponent<type> once for Awake() or Start().  From that point on you may reference the variable rather than having to look up the Component all the time.

I'm unsure whether GetComponent has a performance hit like Find does.

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Is there a buiilt-in way to avoid GetComponent?
« Reply #2 on: July 13, 2012, 07:44:49 PM »
GetComponent isn't very expensive, but it's still better to cache the result.