常用方法:
GetComponent:获取当前物体其他组件类型的引用。
GetComponents:获取当前物体所有组件引用。
GetComponentsInChildren:查找指定类型组件(从自身开始,并搜索所有后代)
GetComponentInChildren:查找指定类型组件(从自身开始,并搜索所有后代,查找到第一个满足条件则结束)
GetComponentsInParent:查找指定类型组件(从自身开始,并搜索所有先辈)
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Component 类 提供了查找组件的功能(从自身、从后代、从先辈)组件的功能
/// </summary>
public class ComponentDemo : MonoBehaviour
{
private void OnGUI()
{
if (GUILayout.Button("transform"))
{
this.transform.position = new Vector3(0,0,10);
}
if (GUILayout.Button("GetComponent"))
{
this.GetComponent<MeshRenderer>().material.color = Color.red;
}
if (GUILayout.Button("GetComponents"))
{
//获取当前组件
var allComponent = this.GetComponents<Component> ();
foreach (var component in allComponent)
{
Debug.Log(component.GetType());
}
}
if (GUILayout.Button("GetComponentsInChildren"))
{
//获取后代物体的指定类型组件(从自身开始)
var allComponent = this.GetComponentsInChildren<MeshRenderer>();
foreach (var component in allComponent)
{
component.material.color = Color.red;
}
}
if (GUILayout.Button("GetComponentsInParent"))
{
//获取先辈物体的指定类型组件(从自身开始)
var allComponent = this.GetComponentsInParent<MeshRenderer>();
foreach (var component in allComponent)
{
component.material.color = Color.red;
}
}
}
}