refer to https://docs.unity3d.com/ScriptReference/Transform.SetParent.html
重感冒,只能摘抄两篇解闷。
1. 参数
parent
需要使用的parent转换。
worldPositionStays
【直译的话当然极其不通顺:世界坐标的停留】
如果为真,则修改parent-relative位置、比例和旋转,使目标对象保持与之前相同的world位置、旋转和比例。
2. 描述
设置转换中的parent。
此方法与parent属性相同,只是它还允许transform保持其局部方向而不是全局方向。
这意味着,例如,如果GameObject之前是在它的parent对象旁边,那么将worldPositionStays
设置为false将会以相同的方式将GameObject移动到它的新parent对象旁边。
worldpositionstay参数的默认值为true。
下图展示了一个在初始坐标上的子物体:
调用SetParent后,worldpositionstay设置为true,如下图所示:
设置为false之后:
注意,子球体处于相同的位置,但是现在相对于新的父立方体。
using UnityEngine;
public class ExampleClass : MonoBehaviour
{
public GameObject child;
public Transform parent;
//Invoked when a button is clicked.
public void Example(Transform newParent)
{
// Sets "newParent" as the new parent of the child GameObject.
child.transform.SetParent(newParent);
// Same as above, except worldPositionStays set to false
// makes the child keep its local orientation rather than
// its global orientation.
child.transform.SetParent(newParent, false);
// Setting the parent to ‘null’ unparents the GameObject
// and turns child into a top-level object in the hierarchy
child.transform.SetParent(null);
}
}
2.1 parent是啥
改变父类将修改父类的相对位置、比例和旋转,但保持世界空间的位置、旋转和比例不变。
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
public GameObject player;
//Invoked when a button is pressed.
public void SetParent(GameObject newParent)
{
//Makes the GameObject "newParent" the parent of the GameObject "player".
player.transform.parent = newParent.transform;
//Display the parent's name in the console.
Debug.Log("Player's Parent: " + player.transform.parent.name);
// Check if the new parent has a parent GameObject.
if (newParent.transform.parent != null)
{
//Display the name of the grand parent of the player.
Debug.Log("Player's Grand parent: " + player.transform.parent.parent.name);
}
}
public void DetachFromParent()
{
// Detaches the transform from its parent.
transform.parent = null;
}
}
2.2 transform是啥
场景中的每个对象都有一个变换。
它用于存储和操作对象的位置、旋转和比例。
每个变换都有一个父变换,允许你分层地应用位置、旋转和缩放。
这是在hierarchy窗格中看到的层次结构。
它们还支持枚举器,所以您可以使用以下语句循环遍历子元素:
using UnityEngine;
public class Example : MonoBehaviour
{
// Moves all transform children 10 units upwards!
void Start()
{
foreach (Transform child in transform)
{
child.position += Vector3.up * 10.0f;
}
}
}