I’m trying to figure out which components in Monobehaviour can be accessed without using GetComponent.
For example, the Transform component and the Renderer component can be accessed directly without using GetComponent. And I just noticed that the GUIText component can also be accessed directly (is this because they’re static classes?). Though every other component I’ve tried (Rigidbody, Light, Collider, etc) requires GetComponent. I’ve looked all through Unity’s documentation and I can’t find any list, and the individual component class pages in the docs don’t even seem to differentiate between them in any way.
How do I know if a specific component requires GetComponent before it can be accessed other than just trial and error?
Take a look at this Unity - Scripting API: MonoBehaviour
You will see in the inherited members that it shows transform, rigidbody, rigidbody2D, renderer and others.
Those can be accessed directly but only Transform is sure to be there. Any other access to the component should be done via a check since it is not sure the component is there.
renderer is most likely there for object you see, a manager will not have a renderer. Again, only transform is granted not to be null, all others are depending on the object.
If you are 1005 sure the component is there then you can call directly.
Though using those variables are slower than caching the component.
One way is to cache using the name:
protected new Rigidbody rigidbody;
void Start(){
rigidbody = base.rigidbody;
}
Check out the component reference, under variables:
If it’s not there, you need to use GetComponent()