int GameObject 上组件的数量,以整数形式表示。
检索当前附加到 GameObject 的所有组件总数。
您可以使用 GetComponentCount
来遍历组件索引,这在与 GameObject.GetComponentAtIndex 一起使用时尤其方便。例如,您可以遍历索引以查找您感兴趣的特定组件的索引,然后保存该索引以供将来使用。
using UnityEngine;
public class IterateComponents : MonoBehaviour { int m_SavedComponentIndex = -1;
void Start() { //Iterate through components on the GameObject for (int i = 0; i < gameObject.GetComponentCount(); i++) { var currComponent = gameObject.GetComponentAtIndex(i); //Check if it is a Rigidbody component if (currComponent.GetType() == typeof(Rigidbody) ) { m_SavedComponentIndex = i; } }
Debug.Log(m_SavedComponentIndex != -1 ? $"Found component at index: {m_SavedComponentIndex}" : "Could not find component"); } }