🤔

NullReferenceException: UnityEngine.Object — GetComponent#

Expand the function you use and confirm you use it correctly:

GetComponent or TryGetComponent#

A component of the target type must be attached to the same GameObject the function is called on. If the value is null after calling, then this assumption is wrong.

  1. The same GameObject has a component matching the argument.
  2. The target components' type actually matches1.
  3. Search the scene for all instances of the caller and check all results (t:ExampleComponent for example).
  4. Assignment must occur before access. Often you would use Awake to get, and Start to use.
information

You can use the RequireComponent attribute to automatically add component dependencies when adding new components in the editor.

GetComponentInChildren#

Only components on active GameObjects are returned unless the includeInactive argument is true.

  1. Either the same object or a child has a matching component.
  2. The component type actually matches1.
  3. Search the scene for all instances of the caller and check all results (t:ExampleComponent for example).
  4. If the component is on an inactive child, provide the includeInactive argument as true.
  5. Assignment must occur before access. Often you would use Awake to get, and Start to use.

GetComponentInParent#

Only components on active GameObjects are returned unless the includeInactive argument is true.

  1. Either the same object or a parent has a matching component.
  2. The component type actually matches1.
  3. Search the scene for all instances of the caller and check all results (t:ExampleComponent for example).
  4. If the component is on an inactive parent, provide the includeInactive argument as true.
  5. Assignment must occur before access. Often you would use Awake to get, and Start to use.

If you're still having issues using these methods, it's often preferable to serialize components via the inspector instead.

warning

Double-check the assignment is actually executed.
Your code may not be called because of an incorrect setup like a misspelt method name.

  1. A common example of this being wrong is Text when using subtypes of TMP_Text.