Unity 关于SetParent方法的使用情况

在设置子物体的父物体时,我们使用SetParent再常见不过了。

  • 但是通常我们只是使用其中一个语法:

    public void SetParent(Transform parent);

使用改方法子对象会保持原来位置,跟使用以下方法效果一样:

复制代码
public Transform tran;
gameObject.transform.parent = tran;
  • 其实它还有一个语法:

    public void SetParent(Transform parent, bool worldPositionStays);

这里多了一个布尔值参数worldPositionStays,作用是指定子级对象在设置父级后是否保持其在世界坐标系中的位置,为true时,子对象保持原来位置,为false时,子对象的位置、旋转和缩放转换为相对于新的父级对象的局部坐标系。

如这里有3个对象:

tran、tran1、tran2,它们坐标分别为:

分别使用以下方法,把tran1、tran2移动到tran下面

复制代码
    public Transform tran;
    public Transform tran1;
    public Transform tran2;
   
    void Start()
    {
        tran1.SetParent(tran);
        tran2.SetParent(tran, false);
    }

它们的坐标变化如下:

我们发现使用 tran1.SetParent(tran)方法,tran1局部坐标改变了,使用tran2.SetParent(tran, false),tran2的局部坐标没有改变。

这在实际的效果就是tran1的位置没有改变,tran2的位置会因父物体的坐标而产生变化。

相关推荐
一线灵1 小时前
Axmol 3.x 输入系统重构:从 Touch/Mouse 到统一 Pointer,再到现代 InputField
重构·游戏引擎
Zwarwolf2 小时前
Godot零散知识点项目汇总
游戏引擎·godot
Mediary2 小时前
Unity is running with Administrator privileges, which isnot supported...
unity
游乐码5 小时前
Unity基础(十四)场景异步加载
unity·游戏引擎
mxwin5 小时前
Unity Shader URP:法线在空间变换上的特殊性
unity·游戏引擎·shader
nnsix5 小时前
Unity 动态批处理、静态批处理、GPU Instaning、SRP Batcher 笔记
笔记·unity·单一职责原则
charlee446 小时前
Unity在安卓端如何调试输出信息
android·unity·adb·游戏引擎·真机调试
TCW11217 小时前
Minetest游戏引擎源代码解析
游戏引擎
_Athie8 小时前
【开发工具】自动创建项目文件夹结构
unity·编辑器