GetComponentAtIndex
Retrieves a reference to a component at a specified index of the GameObject's array of components.
Read time 2 minutesLast updated 4 days ago
Definition
- Type: Method
- Namespace: UnityEngine
- Assembly: UnityEngine.CoreModule
GetComponentAtIndex(int)
Retrieves a reference to a component at a specified index of the GameObject's array of components.
public Component GetComponentAtIndex(int index)
Parameters
The index position in the array of components at which to find the requested object.
Returns
Type | Description |
|---|---|
| Component | A reference to a component at the specified index. If no component is found at the specified index, returns |
Remarks
Using is a stable way to access components on a GameObject because the index of a component stays the same unless components are added or removed.
GetComponentAtIndexAn example use case for this is during UI development. This method throws an exception if the index is out of bounds. Refer to GameObject.GetComponentCount for more information.
using UnityEngine;public class GetComponentAtIndexExample : MonoBehaviour{ public GameObject otherGameObject; void Start() { HingeJoint hinge = otherGameObject.GetComponentAtIndex(5) as HingeJoint; if (hinge != null) { hinge.useSpring = false; } }}
Additional Resources: Component, GameObject.GetComponents
GetComponentAtIndex<T>(int)
Retrieves a reference to a component of type T at a specific index on the specified GameObject.
public T GetComponentAtIndex<T>(int index) where T : Component
Parameters
The index position in the array of components at which to find the requested object.
Returns
Type | Description |
|---|---|
| T | A reference to a component of type |
Remarks
Using is a stable way to access components on a GameObject because the index of a component stays the same unless components are added or removed.
GetComponentAtIndexAn example use case for this is during UI development. This method throws an exception if the index is out of bounds.
Additional Resources: GameObject.GetComponentCount
using UnityEngine;public class GetTComponentAtIndexExample : MonoBehaviour{ public GameObject otherGameObject; void Start() { HingeJoint hinge = otherGameObject.GetComponentAtIndex<HingeJoint>(5); if (hinge != null) { hinge.useSpring = false; } }}
Additional Resources: Component, GameObject.GetComponents