u3d 两个同样obj查找子物体

2023-08-24 13:43:04 浏览数 (2)

代码语言:javascript复制
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
public class Test : MonoBehaviour {

    public GameObject m_tar;

    public GameObject m_tarShadow;
    Vector3 m_tarPos = Vector3.zero;
    Quaternion m_tarQua = Quaternion.identity;
    Dictionary<Transform, Vector3> m_mapPosReset = new Dictionary<Transform, Vector3>();
    Dictionary<Transform, Quaternion> m_mapQuaReset = new Dictionary<Transform, Quaternion>();

    Dictionary<Transform, Transform> m_mapTrans = new Dictionary<Transform, Transform>();

    // Use this for initialization
    void Start () {
        DOTween.Init();
        ChildPosInit2();
    }
	
	// Update is called once per frame
	void Update () {
	
	}

    void ChildPosInit()
    {
        m_tarPos = m_tar.transform.position;
        m_tarQua = m_tar.transform.rotation;
        foreach (var render in m_tar.GetComponentsInChildren<Transform>())
        {
            m_mapPosReset[render.transform] = render.transform.position;
            m_mapQuaReset[render.transform] = render.transform.rotation;
        }
    }

    public void ChildPosResetV1()
    {
        m_tar.transform.DOMove(m_tarPos, 0.5f);
        m_tar.transform.DORotate(m_tarQua.eulerAngles, 0.5f);  
        foreach (var it in m_mapPosReset)
        {
            it.Key.DOMove(it.Value, 0.5f);
        }
        foreach (var it in m_mapQuaReset)
        {
            it.Key.DORotate(it.Value.eulerAngles, 0.5f);
        }

    }

    public void ChildPosReset()
    {
        foreach (var it in m_mapTrans)
        {
            it.Key.DOMove(it.Value.transform.position, 0.5f);
            it.Key.DORotate(it.Value.eulerAngles, 0.5f);
        }

    }

    void ChildPosInit2()
    {
        foreach (var it in m_tar.GetComponentsInChildren<Transform>())
        {
            if (it != m_tar.transform)
            {
                string path = GetParName(it.transform);
                Debug.Log(path);
                m_mapTrans[it.transform] = m_tarShadow.transform.FindChild(path);
            }
        }
    }

    string GetParName(Transform tran)
    {
        if (tran.parent == m_tar.transform)
        {
            return tran.name;
        }
        else
        {
            return GetParName(tran.parent)   "/"   tran.name;
        }
    }
}

注意:子物体不能重名

0 人点赞