Search code examples
c#unity-game-enginegameobject

Unity3D declaring vars or using GetComponent


Is it better to either declare var components at the class level or reference them with GetComponent later in code?

example:

vitals = GetComponent<Vitals>();
weapon = GetComponent<Weapon>();

or should I just use

GetComponent<Vitals>.ApplyHealth(25);

which is better for performance/memory usage?


Solution

  • Storing a reference is better for performance, especially if this is done often. Essentially, unity has to perform a lookup to find the component every time you call getcomponent, which can be very expensive and affect performance. If you are accessing this every fupdate, store a reference. If you access it very infrequently, you can get away with looking it up when you need it.