四个常用其中之二
Component类:
提供了查找物体(后代、先辈和自身)组件的功能
例如:
this.Component<MethRenderer>().material.color = Color.red;//查到到一个物体的材质组件并将其变红
常用方法:
GetComponent<>();获取附加<type>类型的组件
GetComponentInChildren;获取后代包括自身的<type>类型组件
GetComponentsInChildren;获取所有后代包括自身的<type>类型组件
GetComponentInParent();获取先辈包括自身的<type>类型组件
GetComponentsInParent();获取所有先辈包括自身<type>类型组件
需求:
找到当前物体的所有组件:var allComponent = this.GetComponents<Component>();
Transform类:
总结:Transform类提供了查找(父、根、子(子又分为索引和名称查找))变换组件、改变位置、角度、大小功能.
此代码获取了每个子物体的变换组件(Transform)
这里是局部坐标,开启Debug模式时能够看到该组件的私有变量
常用变量和方法:
position;相对于世界坐标系原点的位置
localPosition;相对于父物体的位置
rotation;相对于世界旋转
localRotation;相对于父物体旋转
localScale;相对于父物体缩放比例,(自身缩放比例 * 父物体缩放比例)
lossyScale;物体与模型缩放比例(自身缩放比例 * 父物体缩放比例)
Translate();移动transform在translation的方向和距离。例如: this.transform.Translate(0, 0, 1);//向自身坐标系Z轴移动一米.this.transform.Translate(0, 0, 1, Space.World);//向世界坐标系移动1米。默认是自身的Space.Self;
transform.Rotate(0,10,0,Space.World);沿世界坐标系旋转, transform.Rotate(0,10,0);沿自身坐标系旋转
RotateAround(Vector3.zero,Vector3.up, 1);围绕世界原点的Y旋转1度
Transform rootTF = this.transform.root;获取根物体,它本身是Transform类型
Transform TF = this.transform.parent;//获取父物体的变换组件
this.transform.SetParent(TF, false);//当前子物体认某物体当父物体,并将当前子物体视为localPosition
int count = this.transform.childCount;获取子物体有多少个
for(int i = 0; i < count; i++)
{
Transform childTF = this.transform.GetChild(i);根据索引获取子物体
}