Version: 2020.2
public void SetParent (Transform p);
public void SetParent (Transform parent, bool worldPositionStays);

参数

parent 要使用的父变换。
worldPositionStays 如果为 true,则修改相对于父级的位置、缩放和旋转,使对象保持与之前相同的世界空间位置、旋转和缩放。

描述

设置变换的父级。

此方法与 parent 属性相同,但它还使 Transform 可保持其本地方向而不是其全局方向。 例如,这表示如果 GameObject 以前在其父级旁,则将 worldPositionStays 设置为 false 会以相同方式将 GameObject 移动到位于其新的父级旁。

worldPositionStays 参数的默认值为 true。

下图显示处于其原始位置的子 GameObject:



下面是在 worldPositionStays 设置为 true 的情况下调用 SetParent 之后的外观:



下面是在 worldPositionStays 设置为 false 的情况下调用 SetParent 之后的外观:



请注意,子球体如何处于相同位置,但是现在相对于新的父立方体。

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); } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961