| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- using Sirenix.OdinInspector;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class NewBehaviourScript : MonoBehaviour
- {
- public GameObject 已分组;
- public GameObject 待分组;
- public GameObject 分组目标;
- objTree ObjATree;
- public Dictionary<Mesh, GameObject> objBDic ;
- [Button("测试")]
- void 生成树()
- {
- ObjATree = new objTree(已分组);
- objBDic = new Dictionary<Mesh, GameObject>();
- FindChild(待分组);
- dui(ObjATree, 分组目标);
- }
- void FindChild(GameObject child)
- {
- MeshFilter meshFilter = child.GetComponent<MeshFilter>();
- if (meshFilter != null && meshFilter.sharedMesh != null)
- {
- if (!objBDic.ContainsKey(meshFilter.sharedMesh))
- objBDic.Add(meshFilter.sharedMesh, child);
- }
- for (int i = 0; i < child.transform.childCount; i++)
- FindChild(child.transform.GetChild(i).gameObject);
- }
- void dui(objTree tree,GameObject 当前节点)
- {
- GameObject matchTmpObj;
- if (tree.nodeMesh != null && objBDic.TryGetValue(tree.nodeMesh, out GameObject tmpObj))
- matchTmpObj = tmpObj;
- else
- {
- matchTmpObj = new GameObject();
- matchTmpObj.name = tree.nodeObj.name;
- }
- matchTmpObj.transform.SetParent(当前节点.transform);
- foreach (objTree tmp in tree.children)
- dui(tmp, matchTmpObj);
- }
- [Serializable]
- public class objTree
- {
- public Mesh nodeMesh;
- public GameObject nodeObj;
- public List<objTree> children = new List<objTree>();
- public objTree(GameObject gameObj)
- {
- nodeObj = gameObj;//节点
- try { nodeMesh = nodeObj.GetComponent<MeshFilter>().sharedMesh; }
- catch (Exception) { }
- addObjNode();
- }
- public void addObjNode()
- {
- for (int i = 0; i < nodeObj.transform.childCount; i++)
- {
- children.Add(new objTree(nodeObj.transform.GetChild(i).gameObject));
- }
- }
- }
- }
|