Unity学习记录-MonoBehaivour的重要内容

  • 在一个脚本中,最多只能有一个类继承MonoBehaviour。
  • 创建的脚本只有继承了MonoBehaivour才能挂在GameObject上。
  • 继承MonoBehaivour的脚本只能挂载,不能new

MonoBehaviour中的重要内容

获取脚本依附的物体对象

  • gameobject
1
2
print(this.gameObject);
//打印依附对象的名字

获取物体对象的位置信息

  • transform
1
2
3
print(this.transform.position);//位置
print(this.transform.eulerAngles);//欧拉角
print(this.transform.lossyScale);//缩放

获取脚本是否激活

  • enabled
1
2
3
this.enabled;//返回一个布尔类型

this.enabled = false;//使脚本失活

获取物体自身挂载的脚本

  • GetComponent

根据脚本名获取

  • 返回的是一个基类,如果获取失败会返回空
  • 比较少用
1
2
test t = this.GetComponent("test") as test;
//返回的是一个基类,要进行类型转换

根据type获取

  • 返回的也是一个基类
1
t = this.GetComponent(typeof(test)) as test;

通过泛型获取,推荐使用

  • GetComponent<>()
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);
//利用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>();
//没有参数,因为父对象失活的话子对象也失活
  • 该方法没有参数。因为父对象失活的话子对象也失活