Unity基础-脚本生命周期

1.Unity脚本 和 C#脚本区别?

  • unity脚本继承自MonoBehavior。
  • unity脚本不能new。
  • unity脚本有自己的声明周期。
  • unity脚本作为组件附加在GameObject上面,是GameObject的附加功能(unity的使用是组件模式)

2.GameObject 和 Transform区别

  • GameObject是游戏对象本身。
  • Transform是一个特殊组件(1.必有组件,2.二者互相可获取,3.方法较多)。

  • GameObject:游戏对象的基本操作
gameObject.activeSelf 是否活动
gameObject.tag 标签
gameObject.layer 层
gameObject.name名字
...
  • Transform:位置,旋转,缩放变换操作
transform.Position:(位置)
transform.Rotation:(旋转)
transform.Scale:(缩放)
...

3.生命周期

一个游戏组件的脚本,从开始实例化,直到结束实例被销毁,有一个生命周期。


  • void Reset ()

  • void Awake ()
  • void OnEnable ()
  • void Start()

  • void OnTriggerXXX(Collider other)
  • void OnCollisionXXX (Collision collisionInfo)
  • void OnMouseXXX()

  • void FixedUpdate()
  • void Update()
  • void LateUpdate ()

  • void OnGUI()
  • void OnApplicationPause ()
  • void OnDisable ()
  • void OnDestroy ()

4.脚本操作‘游戏对象’

  • 创建游戏对象
//创建基本几何体
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
  • 克隆游戏对象
//克隆预制体
GameObject.Instantiate(prefab);
  • 查找游戏对象
1.以名字查找
GameObject.Find(string);
2.以标签查找
GameObject.FindGameObjectWithTag(tag);
3.以组件查找
T GameObject.FindObjectOfType() ;
  • 销毁游戏对象
销毁游戏对象,是一个静态方法 
GameObject.Destroy(gameObject)
  • 对象添加组件
public Component AddComponent ()
  • 获取对象组件
1.获取自身的组件
public Component GetComponent(bool includeInactive)
public Component[] GetComponents(bool includeInactive)
2.获取子节点组件
public Component GetComponentInChildren(bool includeInactive)
public Component[] GetComponenstInChildren(bool includeInactive)
3.获取父节点组件
public Component GetComponentInParent(bool includeInactive)
public Component[] GetComponentsInParent(bool includeInactive)
  • 删除对象组件
//切记没有 RemoveComponent() 方法;
1.删除游戏组件
component=go.GetComponnent();
GameObject.Destroy(component);

5.脚本操作Transform

  • 查找子节点
//获取子节点数量
transform.childCount
//按名字(路径)查找
transform.Find(string);
transform.FindChild(string);
//按索引查找
transform.GetChild(int);
//分离子节点
transform.DetachChildren();
  • 设置父节点
//获取根节点
transform.root
//获取父节点
transform.parent
//设置父节点
transform.SetParent(transform);
  • 物体位移
transform.Translate(vector3);
  • 物体旋转
//自转
transform.Rotate(axis,angle);
//公转
transform.RotateAround(point,axis,angle);
  • 看向目标
transform.LookAt(transform);
  • 转换坐标系
//变换位置从物体坐标到世界坐标
transform.TransformPoint(vector3);
//变换位置从世界坐标到自身坐标
transform.InverseTransformPoint(vector3);
//将一个方向从局部坐标变换到世界坐标方向
transform.TransformDirection(vector3);
//将一个方向从世界坐标变换到局部坐标方向
transform.InverseTransformDirection(vector3);

你可能感兴趣的:(Unity基础-脚本生命周期)