Version: 2021.2
LanguageEnglish
  • C#

Transform.SetParent

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Switch to Manual

Declaration

public void SetParent(Transform p);

Declaration

public void SetParent(Transform parent, bool worldPositionStays);

Parameters

parent The parent Transform to use.
worldPositionStays If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before.

Description

Set the parent of the transform.

This method is the same as the parent property except that it also lets the Transform keep its local orientation rather than its global orientation. This means for example, if the GameObject was previously next to its parent, setting worldPositionStays to false will move the GameObject to be positioned next to its new parent in the same way.

The default value of worldPositionStays argument is true.

The image below shows a child GameObject in its original position:



Here’s how it looks after calling SetParent with worldPositionStays set to true:



Here’s how it looks after calling SetParent with worldPositionStays set to false:



Notice how the Child Sphere is in the same position but now relative to the New Parent Cube.

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