NewBehaviourScript.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using Sirenix.OdinInspector;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. public class NewBehaviourScript : MonoBehaviour
  7. {
  8. public GameObject 已分组;
  9. public GameObject 待分组;
  10. public GameObject 分组目标;
  11. objTree ObjATree;
  12. public Dictionary<Mesh, GameObject> objBDic ;
  13. [Button("测试")]
  14. void 生成树()
  15. {
  16. ObjATree = new objTree(已分组);
  17. objBDic = new Dictionary<Mesh, GameObject>();
  18. FindChild(待分组);
  19. dui(ObjATree, 分组目标);
  20. }
  21. void FindChild(GameObject child)
  22. {
  23. MeshFilter meshFilter = child.GetComponent<MeshFilter>();
  24. if (meshFilter != null && meshFilter.sharedMesh != null)
  25. {
  26. if (!objBDic.ContainsKey(meshFilter.sharedMesh))
  27. objBDic.Add(meshFilter.sharedMesh, child);
  28. }
  29. for (int i = 0; i < child.transform.childCount; i++)
  30. FindChild(child.transform.GetChild(i).gameObject);
  31. }
  32. void dui(objTree tree,GameObject 当前节点)
  33. {
  34. GameObject matchTmpObj;
  35. if (tree.nodeMesh != null && objBDic.TryGetValue(tree.nodeMesh, out GameObject tmpObj))
  36. matchTmpObj = tmpObj;
  37. else
  38. {
  39. matchTmpObj = new GameObject();
  40. matchTmpObj.name = tree.nodeObj.name;
  41. }
  42. matchTmpObj.transform.SetParent(当前节点.transform);
  43. foreach (objTree tmp in tree.children)
  44. dui(tmp, matchTmpObj);
  45. }
  46. [Serializable]
  47. public class objTree
  48. {
  49. public Mesh nodeMesh;
  50. public GameObject nodeObj;
  51. public List<objTree> children = new List<objTree>();
  52. public objTree(GameObject gameObj)
  53. {
  54. nodeObj = gameObj;//节点
  55. try { nodeMesh = nodeObj.GetComponent<MeshFilter>().sharedMesh; }
  56. catch (Exception) { }
  57. addObjNode();
  58. }
  59. public void addObjNode()
  60. {
  61. for (int i = 0; i < nodeObj.transform.childCount; i++)
  62. {
  63. children.Add(new objTree(nodeObj.transform.GetChild(i).gameObject));
  64. }
  65. }
  66. }
  67. }