🤔

Referring to members in other scripts#

There are various ways to create a reference between one object and another:

Serialized references#

Serialized references are exposed via the inspector and are defined per-instance. They are fast and configurable.
Learn more.

Singletons#

Singletons are referenced in code and require only one instance of the target type.
Learn more.

GetComponent methods#

Prefer serialized references for their speed and configurability. GetComponent, TryGetComponent, GetComponentInChildren, and other similar methods are perfect for dynamic runtime references, like those resolved during collisions and scene queries.
Learn more.

Find methods#

Avoid the various find methods unless you are debugging or prototyping. These methods are often extremely slow, and even when used from Awake or Start can cause hitches during loading. Learn more about Find methods in the static methods list on GameObject.

Prefer serialized references, singletons, or GetComponent. If you are referencing objects you spawned at runtime, add them to a collection (like a List) when they are created, and reference that object to get your instances instead.

Dependency injection#

Dependency injection (DI) is simply the process of having a reference passed to an object. Serialized references are already a simple form of DI, but you can apply the concept yourself and inject references from managers to other objects under their control.
Learn more.

Alternate methods#

There are other ways to refer to external members, including varied use of the static keyword. Generally these can be avoided until users are familiar with more basic and common concepts.