menu_bookDocumentation
Component.GetComponent, GetComponentInChildren, GetComponentInParent — FindMode and RequireComponent
Component.GetComponent, GetComponentInChildren, GetComponentInParent — FindMode Reference
Components provide convenient lookup methods for finding other components in the hierarchy.
Methods on Component
CSHARP
// Get a component on the same GameObject
T GetComponent<T>( bool includeDisabled = false )
// Get or add a component on the same GameObject
T GetOrAddComponent<T>( bool startEnabled = true )
// Add a component to the same GameObject
T AddComponent<T>( bool startEnabled = true )
// Get all components of type on the same GameObject
IEnumerable<T> GetComponents<T>( bool includeDisabled = false )
// Get a component on this or any descendant GameObject
T GetComponentInChildren<T>( bool includeDisabled = false, bool includeSelf = true )
// Get all components of type on this and descendant GameObjects
IEnumerable<T> GetComponentsInChildren<T>( bool includeDisabled = false, bool includeSelf = true )
// Get a component on this or any ancestor GameObject
T GetComponentInParent<T>( bool includeDisabled = false, bool includeSelf = true )
// Get all components of type on this and ancestor GameObjects
IEnumerable<T> GetComponentsInParent<T>( bool includeDisabled = false, bool includeSelf = true )FindMode Flags
FindMode is a flags enum used by the underlying ComponentList.Get/GetAll. You can use it directly for more control:CSHARP
// Only search enabled components on this object
Components.Get<T>( FindMode.InSelf | FindMode.Enabled )
// Search enabled and disabled in self and all descendants
Components.Get<T>( FindMode.EverythingInSelfAndDescendants )
// Search only ancestors (not self)
Components.GetAll<T>( FindMode.InAncestors | FindMode.Enabled )[RequireComponent] Attribute
If a component property is decorated with [RequireComponent], the engine will automatically find or create the required component when the component is first initialized (during OnAwake):
CSHARP
public class MyComponent : Component
{
// Engine will find or create a Rigidbody on this GameObject
[RequireComponent]
public Rigidbody Body { get; set; }
}This check runs in CheckRequireComponent() during InitializeComponent(), but only when the object is not being deserialized (to avoid overwriting saved references).
Scene-Wide Component Search
CSHARP
// Find all enabled components of type in the entire scene
Scene.GetAllComponents<T>()
// Find by type (non-generic)
Scene.GetAllComponents( typeof(MyComponent) )
Was this helpful?