BehaviorNodeConfig.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using UnityEngine;
  5. namespace Model
  6. {
  7. public class BehaviorNodeConfig: MonoBehaviour
  8. {
  9. public int id;
  10. public string name;
  11. public string describe;
  12. public BehaviorNodeConfig(string name, string _desc, int _id = 0)
  13. {
  14. this.name = name;
  15. describe = _desc;
  16. id = _id;
  17. }
  18. public BehaviorTreeArgsDict GetArgsDict()
  19. {
  20. BehaviorTreeArgsDict dict = new BehaviorTreeArgsDict();
  21. foreach (var item in gameObject.GetComponents<BTTypeBaseComponent>())
  22. {
  23. FieldInfo info = item.GetType().GetField("fieldValue");
  24. ValueBase valueBase = new ValueBase();
  25. if (item.GetType() == typeof (BTEnumComponent))
  26. {
  27. valueBase.SetValueByType(typeof (Enum), info.GetValue(item));
  28. }
  29. else
  30. {
  31. valueBase.SetValueByType(info.FieldType, info.GetValue(item));
  32. }
  33. dict.Add(item.fieldName, valueBase);
  34. }
  35. return dict;
  36. }
  37. public void SetValue(Type type, string fieldName, object value)
  38. {
  39. foreach (BTTypeBaseComponent item in gameObject.GetComponents<BTTypeBaseComponent>())
  40. {
  41. if (fieldName == item.fieldName)
  42. {
  43. object fieldValue = value;
  44. FieldInfo fieldValueinfo = item.GetType().GetField("fieldValue");
  45. if (BehaviorTreeArgsDict.IsEnumType(type))
  46. {
  47. fieldValue = value.ToString();
  48. }
  49. fieldValueinfo.SetValue(item, fieldValue);
  50. }
  51. }
  52. }
  53. public object GetValue(string fieldName)
  54. {
  55. object fieldValue = null;
  56. foreach (BTTypeBaseComponent item in gameObject.GetComponents<BTTypeBaseComponent>())
  57. {
  58. if (fieldName == item.fieldName)
  59. {
  60. FieldInfo fieldValueinfo = item.GetType().GetField("fieldValue");
  61. fieldValue = fieldValueinfo.GetValue(item);
  62. }
  63. }
  64. return fieldValue;
  65. }
  66. public NodeProto ToNodeProto()
  67. {
  68. return NodeConfigToNodeProto(this);
  69. }
  70. private static NodeProto NodeConfigToNodeProto(BehaviorNodeConfig nodeProto)
  71. {
  72. NodeProto nodeData = new NodeProto();
  73. nodeData.nodeId = nodeProto.id;
  74. nodeData.name = nodeProto.name;
  75. nodeData.describe = nodeProto.describe;
  76. nodeData.args_dict = nodeProto.GetArgsDict();
  77. nodeData.children = new List<NodeProto>();
  78. foreach (Transform child in nodeProto.gameObject.transform)
  79. {
  80. BehaviorNodeConfig nodeConfig = child.gameObject.GetComponent<BehaviorNodeConfig>();
  81. NodeProto childData = NodeConfigToNodeProto(nodeConfig);
  82. nodeData.children.Add(childData);
  83. }
  84. return nodeData;
  85. }
  86. }
  87. }