MonoBehavior基类:
1.创建的脚本默认都继承MonoBehavior 继承了它才能够挂载在GameObject上
2.继承了MonoBehavior的脚本不能new只能挂!!!!!!
3.继承了MonoBehavior的脚本不要去写构造函数,因为我们不会去new它,写构造函数没有任何意义
4.继承了MonoBehavior的脚本可以在一个对象上挂多个(如果没有加DisallowMultipleComponent)
5.继承MonoBehavior的类也可以再次被继承,遵循面向对象继承多态的规则
不继承MoNoBehavior的类:
1.不继承MoNo的类 不能挂载在GameObject上
2.不继承MoNo的类 想怎么写怎么写 如果要使用需要自己new
3.不继承MoNo的类 一般是单例模式的类 (用于管理模块) 或者数据,结构类(用于存储数据)
4.不继承MoNo的类 不用保留默认出现的几个函数
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Monodemo : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
#region 知识点一 重要成员
//1.获取依附的GameObject
print(this.gameObject.name);
//2.获取依附的GameObject的位置信息
//得到对象的位置信息
print(this.transform.position);//位置
print(this.transform.eulerAngles);//角度
print(this.transform.lossyScale);//缩放大小
//这种写法和上面是一样的效果,都是得到依附的对象的位置信息
//this.gameobject.transform
//3.获取脚本是否激活
this.enabled = false;
//获取别的脚本对象 依附的gameobject和transform位置信息
print(otherLesson3.gameObject.name);
print(otherLesson3.transform.position);
#endregion
#region 知识点二 重要方法
//得到依附对象上挂载的其他脚本
//1.得到自己挂载的单个脚本
//根据脚本名获取
//获取脚本的方法 如果获取失败 就是没有对应的脚本 会默认返回空
Lesson3_Text t = this.GetComponent("Lesson3_Text") as Lesson3_Text;
print(t);
//根据Type获取
t = this.GetComponent(typeof(Lesson3_Text)) as Lesson3_Text;
print(t);
//根据泛型获取 建议使用泛型获取 因为不用二次转换
t = this.GetComponent<Lesson3_text>();
print(t);
//只要你能得到场景中别的对象或者对象依附的脚本
//那你就可以获取到它的所有信息
//2,得到自己挂载的多个脚本
Monodemo[] array = this.GetComponents<Monodemo>();
print(array.Length);
List<Monodemo> list = new List<Monodemo>();
this.GetComponents<Monodemo>(list);
print(list.Count);
//3.得到子对象挂载的脚本(它默认也会找自己身上是否挂载脚本)
//函数是有一个参数的 默认不传 是false 意思就是 如果子对象失活 是不会去找这个对象上是否有某个脚本的
//如果true 即使 失活 也会找
t= this.GetComponentInChildren<Monodemo>(true);
print(t);
Monodemo[] lts = this.GetComponentsInChildren<Monodemo>(true);
print(lts.Length);
List<Monodemo> list2 = new List<Monodemo>();
this.GetComponentsInChildren<Monodemo>(true, list2);
print(list2.Count);
//4.得到父对象挂载的脚本(它默认也会找自己身上是否挂载该脚本)
t = this.GetComponentInParent<Monodemo>();
print(t);
lts = this.GetComponentsInParent<Monodemo>();
print(lts.Length);
//它也有list的 和上面一样
//5.尝试获取脚本
Monodemo l3t;
//提供了一个更加安全的 获取单个脚本的方法 如果得到了 会返回true
//然后再来进行逻辑处理即可
if(this.TryGetComponent<Monodemo>(out l3t))
{
}
#endregion
}
// Update is called once per frame
void Update()
{
}
}