Unity SetParent第二个参数worldPositionStays的意义

初学Unity的小知识:
改变对象的父级有三种调用方式,如下:

transMe.SetParent(transParent,true);
transMe.SetParent(transParent,false);
transMe.parent = transParent;

具体有什么区别呢,这里写一个测试例子来详细说明,先上代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test333 : MonoBehaviour
{
    public Transform transMe;   //测试对象
    public Transform transParent;

    public bool toParent1;  //worldPositionStays = true
    public bool toParent2;  //worldPositionStays = false
    public bool toParent3;  //直接改parent

    public bool reset;
    void Start()
    {
        resetme();
    }

    private void resetme()
    {
        transMe.SetParent(null, false);
        transMe.position = new Vector3(0f, 3f, 0f);
    }

    // Update is called once per frame
    void Update()
    {
        if (reset)
        {
            reset = false;
            resetme();
        }
        if (toParent1)
        {
            transMe.SetParent(transParent,true);
            toParent1 = false;
        }

        if (toParent2)
        {
            toParent2 = false;
            transMe.SetParent(transParent, false);
        }

        if (toParent3)
        {
            toParent3 = false;
            transMe.parent = transParent;
        }
    }
}

下图中:红色是parent,在(1,1,1),白色盒子是要改变parent的对象,在(0,3,0)默认位置。
在这里插入图片描述

我们来看下几种变化:

第一种worldPositionStays为True

transMe.SetParent(transParent,true);

第二个参数是True。标识需要保留当前的世界坐标,很好理解,运行后,勾选toParent1,我们看到位置没有任何变化,只是改变了父子级。
在这里插入图片描述

第二种worldPositionStays为False

transMe.SetParent(transParent, false);

我们运行后发现改变父子级后,会把当前的Local坐标叠加到新的位置,明显看到是parent的位置上加上了(0,3,0)坐标后的位置。
在这里插入图片描述

第三种改变parent

transMe.parent = transParent;

运行后和第一种相同,都是保留世界坐标。

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值