这是我参与8月更文挑战的第14天,活动详情查看:8月更文挑战
一,获取组件
- 直接获取组件
GetComponent<脚本或者组件名>(); - 在子物体中查找指定组件
GetComponentInChildren<脚本或者组件名>(); - 查找子物体中所有指定组件
GetComponentsInChildren<脚本或者组件名>(); - 获取父物体查找指定组件 `GetComponentInParent<>(脚本或者组件名) ;
- 查找子物体中所有指定组件
GetComponentsInParent<脚本或者组件名>();包括物体本身以及下面所有的子物体
- 代码示例
using UnityEngine;
using UnityEngine.UI;
public class GetComponentTest : MonoBeh
{
void Start()
{
// 获取脚本挂载本身的Text组件
AudioSource audio1 = GetComponent<AudioSource>();
// 获取脚本挂载物体子物体身上的Text组件 (找到的第一个)
AudioSource audio2 = GetComponentInChildren<AudioSource>();
// 获取脚本挂载物体所有子物体身上的Text组件
AudioSource[] audio3 = GetComponentsInChildren<AudioSource>();
// 获取脚本挂载物体所有父物体身上的Text组件
AudioSource audio4 = GetComponentInParent<AudioSource>();
// 获取脚本挂载物体所有子物体身上的Text组件 (会查找父物体及父物体的其他子物体)
AudioSource[] audio5 = GetComponentsInParent<AudioSource>();
}
}
添加组件
- 代码动态添加: gameObejct.AddComponent<>(); //动态添加组件 <脚本名称>
- 示例:
程序运行会给挂载脚本物体自动添加Text组件,代码如下:
void Start()
{
gameObject.AddComponent<AudioSource>();
}
- 编辑扩展 [RequireComponent(typeof())] //添加组件(扩展编辑器)
写法:放在类名的上面
[RequireComponent(typeof(AudioSource))]
public class GetComponentTest : MonoBehaviour
{
}
实例图示:
解释:运行时代码挂载物体身上没有AudioSource这个组件,这会自动添加一个
移除组件
Unity 没有提供类似AddComponent 的 Remove... 方法,所以移除组件时要这么写:
Destroy(GetComponent<组件名>());
当GetComponent<组件名>()不为空时,它会为我们移除组件,当GetComponent<组件名>()为空时,也不会报错,因为GetComponent<组件名>() 这个即使是没有获取到组件,也不算数违反语法;而Destroy这个方法,即使直接Destroy(null); 这样写也没有问题。
示例演示
将代码挂载场景任意物体上分别按下键盘上A,S,D 看下Inspector面板效果:
- A:添加组件
- S:获取组件
- D:移除组件
public class GetComponentTest : MonoBehaviour
{
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
// 添加组件
gameObject.AddComponent<AudioSource>();
}
else if (Input.GetKeyDown(KeyCode.S))
{
// 获取组件
AudioSource audio= gameObject.GetComponent<AudioSource>();
// 使用组件
audio.volume = 0;
}
else if (Input.GetKeyDown(KeyCode.D))
{
// 移除组件
Destroy(gameObject.GetComponent<AudioSource>());
}
}
}