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

相关推荐
不伤欣20 小时前
游戏设计模式 - 子类沙箱
游戏·unity·设计模式
Magnum Lehar1 天前
vulkan游戏引擎test文件memory实现
游戏引擎
Magnum Lehar1 天前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎
快乐觉主吖1 天前
Unity的日志管理类
android·unity·游戏引擎
WarPigs1 天前
Unity性能优化笔记
笔记·unity·游戏引擎
T.D.C2 天前
【业务框架】3C-相机-Cinemachine
unity
一线灵2 天前
跨平台游戏引擎 Axmol-2.6.1 发布
游戏引擎
Clank的游戏栈2 天前
Unity基于GraphView的可视化关卡编辑器开发指南
unity·编辑器·游戏引擎
海尔辛2 天前
Unity UI 性能优化--Sprite 篇
ui·unity·性能优化
三巧3 天前
Godot 敌人生成半径和围墙不匹配,导致敌人错误的生成在围墙外的解决代码
游戏引擎·godot