#唐老狮unity课程笔记#
获取和设置父对象
获取父对象
print(this.transform.parent);
设置父对象 -- 断绝父子关系
this.transform.parent = null;
设置父子关系 -- 建立父子关系(认爸爸)
this.transform.parent = GameObject.Find("father)").transform;
通过API来进行父子关系的设置
this.transform.SetParent(null); // 断绝父子关系
this.transform.SetParent(GameObject.Find("father").transform); // 建立父子关系(认爸爸)
SetParent中的参数
参数一 :我的父亲
参数二: 是否保留世界坐标的 位置 角度 缩放 信息
true 会保留 世界坐标下的状态 和 父对象 进行计算 得到本地坐标系的信息
false 不会保留 会直接把世界坐标系下的 位置角度缩放 直接赋值到 本地坐标系下
this.transform.SetParent(GameObject.Find("father").transform, true);
抛妻弃子
和自己的儿子(子对象)断绝关系 没有父子关系了
this.transform.DetachChildren();
获取子对象
按名字查找子对象
Find()方法可以找到失活的子对象 GameObject相关的查找找不到失活的
Find()只能找到儿子,找不到孙子 而且他需要知道父亲是谁
this.transform.Find("cube"); // FindChildren() 已经被弃用了,用 Find()就行
遍历儿子
如何得到多少个子对象?
失活的子对象也算数
孙子(子对象的子对象)不算数
print(this.transform.childCount);
通过索引号 去得到自己对应的儿子
编号超出了儿子的数量范围,会直接报错
返回值 是 transform 可以得到对应儿子的 位置相关信息
this.transform.GetChild(0);
// for循环遍历
for (int i = 0; i < this.transform.childCount; i++)
{
print(this.transform.GetChild(i));
}
儿子(子对象)的操作
提前声明好public的Transform类型的变量son,不要忘记在unity中将目标子对象拖进去得到该对象
判断自己的爸爸(父对象)是谁
一个对象判断自己是不是括号里对象的儿子
son.IsChildOf(this.transform); // bool值
if (son.IsChildOf(this.transform))
{
print("是儿子");
}
得到自己作为儿子的编号
print(son.GetSiblingIndex());
把自己设置为第一个儿子
son.SetAsFirstSibling();
把自己设置成最后一个儿子
son.SetAsLastSibling();
把自己设置成指定编号的儿子
如果超出范围(负数或者更大的数) ,不会报错 ,会直接设置成最后一个编号
son.SetSiblingIndex(-1);