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 小时前
Unity基础:UI组件详解:Toggle开关的状态控制
ui·unity·lucene
mxwin2 小时前
Unity URP 法线贴图:世界空间 vs 切线空间 深度解析两种法线贴图格式在实时渲染中的核心差异、适用场景与性能权衡
unity·游戏引擎·贴图
℡枫叶℡1 天前
Unity - 全局配置Unity工程的资源检索的目录
unity·资源检索配置
mxwin1 天前
Unity URP 下 TBN 矩阵学习 切线空间、tangent.w 与镜像 UV 的那些坑
学习·unity·矩阵·shader
程序猿多布1 天前
Unity导表工具解决方案-Luban使用教程
unity·luban
mxwin1 天前
Unity URP Shader 混合模式完全指南
unity·游戏引擎
mxwin1 天前
Unity URP 下 HDR 与 Tonemapping 的 Shader 意识
unity·游戏引擎
沉默金鱼1 天前
U3D高级编程:主程手记——第二章2.1读书笔记
unity·游戏引擎
mxwin2 天前
Unity Shader 深度写入与关闭ZWrite Off · 半透明排序 · 粒子穿插
unity·游戏引擎·shader
张老师带你学2 天前
宇宙飞船完整Unity项目
科技·游戏·unity·游戏引擎·模型