BehaviorNodeConfig.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 (var 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 NodeConfigToNodeProto(this);
  68. }
  69. private static NodeProto NodeConfigToNodeProto(BehaviorNodeConfig nodeProto)
  70. {
  71. NodeProto nodeData = new NodeProto();
  72. nodeData.nodeId = nodeProto.id;
  73. nodeData.name = nodeProto.name;
  74. nodeData.describe = nodeProto.describe;
  75. nodeData.args_dict = nodeProto.GetArgsDict();
  76. nodeData.children = new List<NodeProto>();
  77. foreach (Transform child in nodeProto.gameObject.transform)
  78. {
  79. BehaviorNodeConfig nodeConfig = child.gameObject.GetComponent<BehaviorNodeConfig>();
  80. NodeProto childData = NodeConfigToNodeProto(nodeConfig);
  81. nodeData.children.Add(childData);
  82. }
  83. return nodeData;
  84. }
  85. }
  86. }