1.獲取和設定父物件
子物件在世界坐標系下的位置是加法運算:子物件在世界坐標系下的位置 = 子物件的位置 + 父物件的位置
子物件在世界坐標系下的縮放是乘法運算:子物件在世界坐標系下的位置 = 子物件的位置 + 父物件的位置
現有:

Lesson9腳本中的代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lesson9 : MonoBehaviour
{
void Start()
{
//獲取父物件
//可以通過Transform 獲取我自己的父物件是誰
print(this.transform.parent.name);
//設定父物件
//1.斷絕父子關系
this.transform.parent = null;
//2.找個新父親(需要賦值一個物件的transform)
this.transform.parent = GameObject.Find("Father2").transform;
//3.通過API來進行父子關系的設定
//引數1 父物件的Transform
//引數2 是否保留本物件在世界坐標系下的位置、角度、縮放資訊
// 如果填true,則會保留世界坐標系下的狀態和父物件進行計算 得出想對父物件的本地坐標系的資訊
// 如果填false,則不會進行計算,直接把在世界坐標系下的資訊 賦值到在本地坐標系中
this.transform.SetParent(GameObject.Find("Father2").transform, true);
}
}
運行:

2.拋棄所有子物件
現有:
Lesson9腳本的代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lesson9 : MonoBehaviour
{
void Start()
{
//與自己的所有子物件 斷絕關系
this.transform.DetachChildren();
}
}
運行:

3.獲取子物件
現有:

Lesson9腳本的代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lesson9 : MonoBehaviour
{
void Start()
{
//1.按名字查找兒子
// 回傳一個兒子的transform資訊
// 只能找兒子,找不了孫子
// transform.Find能找到失活的兒子,而GameObject相關的查找 是找不到失活物件的
print(this.transform.Find("Son2").name);
//2.得到有多少個兒子(失活的兒子也算,孫子不算)
print(this.transform.childCount);
//3.通過索引,去得到自己對應的兒子
// 回傳值是transform,可以得到對應的兒子位置相關資訊
// 注意 索引越界會報錯
this.transform.GetChild(0);
//4.遍歷兒子
for (int i = 0; i < this.transform.childCount; i++)
{
print(this.transform.GetChild(i).name);
}
}
}
運行:

4.兒子的操作
現有:

Lesson9腳本的代碼
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lesson9 : MonoBehaviour
{
//要進行以下操作的兒子
public Transform son;
void Start()
{
//1.判斷傳入的這個物件是不是自己父親
if (son.IsChildOf(this.transform))
{
print("傳入的這個物件是我父親");
}
//2.得到自己作為兒子的編號
print(son.GetSiblingIndex()); //將會列印 0
//3.把自己設定成第一個兒子
son.SetAsFirstSibling();
//4.把自己設定成最后一個兒子
son.SetAsLastSibling();
//5.把自己設定為指定個兒子
// 索引越界也不會報錯,而是直接把它設定到最后一個
son.SetSiblingIndex(1);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/505501.html
標籤:其他
