核心类
Component 类
两种制作按钮的方式
void OnGUI()
{ // 四个参数分别是按钮左上顶点的向右偏移,向下偏移,按钮宽度,高度
if (GUI.Button(new Rect(0, 100, 50, 200), "I am a button"))
{
print("You clicked the button!");
}
if (GUILayout.Button("I am a button"))
{
print("You clicked the button!");
}
}
两种方式分别对应两种组织 UI 界面的方式:Fixed Layout vs Automatic Layout
点击改变物体颜色
void OnGUI()
{
if (GUILayout.Button("Turn color"))
GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1);
}
获取物体的所有组件
void OnGUI()
{
if (GUILayout.Button("Get Components"))
{
Component[] components = GetComponents<Component>();
foreach (var item in components)
print(item);
}
}
获取物体及其所有子物体的组件
获取顺序采用深度优先搜索
void OnGUI()
{
if (GUILayout.Button("Get Components"))
{
var components = this.GetComponentsInChildren<MeshRenderer>();
foreach (var item in components)
{
item.material.color = Color.red;
}
}
}
总结:Component 类提供了(在当前物体、后代、先辈中)查找组件的功能。
Transform 类
遍历所有子物体的变换组件:
void OnGUI()
{
if (GUILayout.Button("foreach - transform"))
{
foreach (Transform child in transform)
{ // child 为每个子物体的变换组件
print(child.name);
}
}
}
常用属性
注意:编辑器中显示的的位置、旋转、缩放都是 Local 的。
position
,localPosition
rotation
,localRotation
localScale
,lossyScale
编辑器中的缩放指的是相比父物体的缩放比例。
localScale
指的是相对父物体缩放比例;
lossyScale
(只读)指的是物体与原模型缩放比例(自身缩放比例 * 父物体缩放比例)。root
:获取根物体变换组件;parent
:获取父物体变换组件;childCount
:子物体数量。
常用方法
Translate
:移动;Rotate
:旋转;RotateAround
:选定点和轴旋转;SetParent
:设置父物体,设为 null 即可解除关系;Find
:根据名称获取子物体(支持用路径查找孙子,但不推荐);
总结:Transform 类提供了查找(父、根、子)变换组件、改变位置、角度、缩放等功能。