场景中的每一个对象都有一个Transform。用于储存并操控物体的位置、旋转和缩放。每一个Transform可以有一个父级,允许你分层次应用位置、旋转和缩放。可以在Hierarchy面板查看层次关系。他们也支持计数器(enumerator),因此你可以使用循环遍历子对象。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Transfrom 提供了查找(父、根、子)变换组件功能、改变位置、角度、大小功能
/// </summary>
public class TransfromDemo : MonoBehaviour
{
public Transform tf;
private void OnGUI()
{
if (GUILayout.Button("foreach -- transfrom"))
{
//场景中的每一个对象都有一个Transfrom,用于存储并操控物体的位置、旋转、缩放。
//每一个Transfrom可以有一个父级,允许你分层次应用位置、旋转和缩放。
//可以在Hierarchy面板查看层次关系。他们也支持计算器,因此你可以使用循环遍历子对象
foreach (Transform child in this.transform)
{
//child为每个子物体的变换组件
print(child.name);
}
}
if (GUILayout.Button("root"))
{
//获取根物体变换组件
Transform rootTF = this.transform.root;
Debug.Log(rootTF.name);
}
if (GUILayout.Button("parent"))
{
//获取父物体变换组件
Transform parentTF = this.transform.parent;
Debug.Log(parentTF.name);
}
if (GUILayout.Button("Setparent"))
{
//设置父物体
//当前物体的位置 视为世界坐标position
//this.transform.SetParent(tf,true);
//当前物体的位置 视为localPosition
this.transform.SetParent(tf,false);
}
if (GUILayout.Button("Find"))
{
//根据名称获取子物体
Transform tf = this.transform.Find("子物体名称");
Debug.Log(tf.name);
Transform tf1 = this.transform.Find("子物体名称/子物体名称");
Debug.Log(tf1.name);
}
if (GUILayout.Button("GetChild"))
{
int count = this.transform.childCount;
//根据索引获取子物体 不能获取孙子物体
for (int i = 0;i < count;i++)
{
Transform childTf = this.transform.GetChild(i);
}
}
//练习:在层级未知情况下查找子物体
if (GUILayout.Button("pos / scale"))
{
//物体相对于世界坐标系原点的位置
//this.transform.position;
//物体相对于父物体轴心点的位置
//this.transform.localPosition;
//相对于父物体缩放比例 1 2 1
//this.transform.localScale;
//理解为:物体与模型缩放比例(自身缩放比例 * 父物体缩放比例)
//this.transfrom.lossyScale
//如:父物体localScale为3 当前物体localScale为2
// lossyScale则为6
}
if (GUILayout.Button("Translate"))
{
//向自身坐标系 Z轴 移动1米
this.transform.Translate(0, 0, 1);
//向世界坐标系 Z轴 移动1米
//this.transform.Translate(0, 0, 1, Space.World);
}
if (GUILayout.Button("Rotate"))
{
//向自身坐标系 y轴 旋转10度
//this.transform.Rotate(0, 10, 0);
//向世界坐标系 y轴 旋转10度
this.transform.Rotate(0, 10, 0, Space.World);
}
if (GUILayout.RepeatButton("RotateAround"))
{
//向世界坐标系 绕y轴旋转
transform.RotateAround(Vector3.zero, Vector3.up, 1);
}
}
}