Summary
Use GetComponent to find a component on the same GameObject. Use Inspector references to connect a script to another object, manager, prefab, audio clip or UI component. The beginner rule is simple: same object, GetComponent; different object, Inspector reference. (course lab series, see source-csharp-unity-labs)
Comparison table
| Dimension | GetComponent | Inspector reference |
|---|---|---|
| Where target usually lives | Same GameObject | Another GameObject, asset or component |
| Setup location | Code | Inspector |
| Typical field | private Rigidbody2D rb; | [SerializeField] private GameManager gameManager; |
| Main strength | Avoids manual dragging for same-object components | Makes scene wiring visible and flexible |
| Main failure | Component missing from same object | Slot left empty or wrong object dragged in |
| Best validation | if (rb == null) Debug.LogError(...) | if (gameManager == null) Debug.LogError(...) |
| Performance | Fine when cached in Awake or Start | No runtime search cost |
When to choose GetComponent
Choose GetComponent when:
- the script needs another component on the same object
- the dependency is structural, such as a player controller needing its own
Rigidbody2D - you want setup to be less manual
- the reference should be cached once in
AwakeorStart
Example:
private Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
if (rb == null)
Debug.LogError("[Player] Rigidbody2D missing.");
}When to choose Inspector references
Choose an Inspector reference when:
- the target is another object, such as a
GameManager - the target is an asset, such as a prefab or audio clip
- designers or tutors need to see the connection in the scene
- several scene objects may use different assigned targets
Example:
[SerializeField] private GameManager gameManager;
private void Start()
{
if (gameManager == null)
Debug.LogError("[CoinPickup] GameManager not assigned.");
}Related
unity-getcomponent · unity-inspector-references · unity-object-communication · unity-gamemanager-pattern · nullreferenceexception · component