I was wondering if there was a better or more efficient way of accessing a function from a script on a gameObject rather than using GetComponent.
What I currently have(it works):
var target : GameObject;
var targetGravityBody : GravityBody;
targetGravityBody = target.GetComponent(GravityBody);
But it seems like a lot of code just to access a function. Does everybody do this?
Getting a component is always a two step process…get the game object then get the component from the game object. But there are many situations where one or both are done for you or implied. For example, it appears that you are initializing ‘target’ by dragging and dropping in the inspector. You can also initialize ‘targetGravityBody’ in the same way. That is just drag the game object with the component onto the 'targetGravityBody variable in the inspector, and unity will fixup a link directly to the component. You could then get rid of ‘target’ altogether.
Unless you need to do null checks, you can also combine things so you don’t need interim variables. For performance reasons, it is better to use the interim variables if you are going to make repeated references to the component. But for a single reference: