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