Meshselect.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using Org.BouncyCastle.Asn1.Ocsp;
  2. using Sirenix.OdinInspector;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using UnityEngine;
  7. public class Meshselect : MonoBehaviour
  8. {
  9. public GameObject modelA;
  10. public GameObject modelB;
  11. //public GameObject fenzumubiao;
  12. objTree ObjATree;
  13. public Dictionary<string, GameObject> objBDic;
  14. [Button("测试")]
  15. void CreateTree()
  16. {
  17. ObjATree = new objTree(modelA);
  18. objBDic = new Dictionary<string, GameObject>();
  19. FindChild(modelB);
  20. GameObject newFenzumubiao = new GameObject("分组目标");
  21. HierarchicalMatching(ObjATree, newFenzumubiao);
  22. modelB.transform.SetParent(newFenzumubiao.transform);
  23. modelB.name = "没配对上的";
  24. }
  25. void FindChild(GameObject child) //收集未分组的mesh
  26. {
  27. MeshFilter meshFilter = child.GetComponent<MeshFilter>();
  28. if (meshFilter != null && meshFilter.sharedMesh != null)
  29. {
  30. if (!objBDic.ContainsKey(meshFilter.sharedMesh.name))
  31. objBDic.Add(meshFilter.sharedMesh.name, child);
  32. }
  33. for (int i = 0; i < child.transform.childCount; i++)
  34. FindChild(child.transform.GetChild(i).gameObject);
  35. }
  36. void HierarchicalMatching(objTree tree, GameObject NowPoint) //按层级匹配
  37. {
  38. GameObject matchTmpObj;
  39. if (tree.nodeMesh != null && objBDic.TryGetValue(tree.nodeMesh.name, out GameObject tmpObj))
  40. matchTmpObj = tmpObj;
  41. else
  42. {
  43. matchTmpObj = new GameObject();
  44. matchTmpObj.name = tree.nodeObj.name;
  45. }
  46. matchTmpObj.transform.SetParent(NowPoint.transform);
  47. foreach (objTree tmp in tree.children)
  48. HierarchicalMatching(tmp, matchTmpObj);
  49. }
  50. //
  51. [Serializable]
  52. public class objTree
  53. {
  54. public Mesh nodeMesh;
  55. public GameObject nodeObj;
  56. public List<objTree> children = new List<objTree>();
  57. public objTree(GameObject gameObj)
  58. {
  59. nodeObj = gameObj;//节点
  60. MeshFilter meshFilter = nodeObj.GetComponent<MeshFilter>();
  61. if (meshFilter != null && meshFilter.sharedMesh != null)
  62. nodeMesh = nodeObj.GetComponent<MeshFilter>().sharedMesh;
  63. addObjNode();
  64. }
  65. public void addObjNode()
  66. {
  67. for (int i = 0; i < nodeObj.transform.childCount; i++)
  68. {
  69. children.Add(new objTree(nodeObj.transform.GetChild(i).gameObject));
  70. }
  71. }
  72. }
  73. }