Unity学习记录-MonoBehaivour的重要内容
- 在一个脚本中,最多只能有一个类继承MonoBehaviour。
- 创建的脚本只有继承了MonoBehaivour才能挂在GameObject上。
- 继承MonoBehaivour的脚本只能挂载,不能new
MonoBehaviour中的重要内容
获取脚本依附的物体对象
1 2
| print(this.gameObject);
|
获取物体对象的位置信息
1 2 3
| print(this.transform.position); print(this.transform.eulerAngles); print(this.transform.lossyScale);
|
获取脚本是否激活
1 2 3
| this.enabled;
this.enabled = false;
|
获取物体自身挂载的脚本
根据脚本名获取
1 2
| test t = this.GetComponent("test") as test;
|
根据type获取
1
| t = this.GetComponent(typeof(test)) as test;
|
通过泛型获取,推荐使用
1
| t = this.GetComponent<test>();
|
获取物体自身挂载的多个脚本,返回一个对象数组
1 2 3 4 5 6 7 8
| Lesson3[] array = this.GetComponents<Lesson3>();
print(array.Length);
List<Lesson3> list = new List<Lesson3>(); this.GetComponents<Lesson3>(list);
print(list.Count);
|
获取物体子对象挂载的脚本
- GetComponentInChildren<>()
- 此方法也会找到自己身上是否挂载了该脚本
- 只要是比自身层级低的物体就能找
1 2 3 4 5 6
| test t = this.GetComponentInChildren<test>(true);
print(t);
test[] arr = this.GetComponentsInChildren<test>(); print(arr.Length);
|
- 括号内参数为一个布尔值。默认为false。表示是否检测失活的子对象
获取父对象挂载的脚本
- GetComponentInParent<>()
- 不会检测自身
- 只要是比自己层级高的就会检测到
1 2
| t = this.GetComponentInParent<test>();
|