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的位置会因父物体的坐标而产生变化。

相关推荐
五仁烧饼5 小时前
Unity Addressables 静默资源策略
游戏·unity·addressables
ue星空12 小时前
【Godot】更换编辑器外观主题
编辑器·游戏引擎·godot
fanfan_hongyun13 小时前
unity 与cad 坐标系映射
unity·游戏引擎
神码编程15 小时前
【Unity】 HTFramework框架(七十)MultiChoiceDropdown可多选的下拉菜单
unity·游戏引擎·ugui·dropdown·下拉菜单
ue星空17 小时前
Godot 2D像素游戏移动抖动、模糊问题解决方案
游戏·游戏引擎·godot
淡海水17 小时前
15-07-YooAsset面试篇-Unity性能优化与内存管理
java·unity·面试·性能优化·c#·游戏引擎
ue星空17 小时前
【Godot】AudioStreamPlayer2D音频播放
游戏引擎·音视频·godot
zhchyun20082 天前
# 【Unity UI 进阶】仿 Element UI 打造企业级 Unity UI 组件库(03)
unity
淡海水2 天前
15-02-YooAsset面试篇-Unity架构设计与源码
java·unity·面试·c#·游戏引擎·yooasset
郝学胜-神的一滴2 天前
中级OpenGL教程 030:gl_FragCoord解锁区域渲染与深度可视化新姿势
c++·unity·游戏引擎·图形渲染·unreal engine·opengl