BehaviorTreeComponent.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using Common.Base;
  5. namespace Model
  6. {
  7. public class BehaviorTreeComponent : Component<World>, IAssemblyLoader, IStart
  8. {
  9. private Dictionary<int, BehaviorTree> behaviorTrees;
  10. private Dictionary<NodeType, Func<NodeConfig, Node>> dictionary =
  11. new Dictionary<NodeType, Func<NodeConfig, Node>>();
  12. public void Load(Assembly assembly)
  13. {
  14. this.behaviorTrees = new Dictionary<int, BehaviorTree>();
  15. dictionary = new Dictionary<NodeType, Func<NodeConfig, Node>>();
  16. Type[] types = assembly.GetTypes();
  17. foreach (Type type in types)
  18. {
  19. object[] attrs = type.GetCustomAttributes(typeof(NodeAttribute), false);
  20. if (attrs.Length == 0)
  21. {
  22. continue;
  23. }
  24. NodeAttribute attribute = attrs[0] as NodeAttribute;
  25. Type classType = type;
  26. if (this.dictionary.ContainsKey(attribute.Type))
  27. {
  28. throw new GameException($"已经存在同类节点: {attribute.Type}");
  29. }
  30. this.dictionary.Add(attribute.Type, config => (Node)Activator.CreateInstance(classType, config));
  31. }
  32. }
  33. public void Start()
  34. {
  35. TreeConfig[] configs = World.Instance.GetComponent<ConfigComponent>().GetAll<TreeConfig>();
  36. foreach (TreeConfig proto in configs)
  37. {
  38. behaviorTrees[proto.Id] = CreateTree(proto);
  39. }
  40. }
  41. public BehaviorTree this[int id]
  42. {
  43. get
  44. {
  45. BehaviorTree behaviorTree;
  46. if (!this.behaviorTrees.TryGetValue(id, out behaviorTree))
  47. {
  48. throw new GameException($"无法找到行为树: {id}");
  49. }
  50. return behaviorTree;
  51. }
  52. }
  53. private Node CreateOneNode(NodeConfig proto)
  54. {
  55. NodeType nodeType = proto.Type;
  56. if (!this.dictionary.ContainsKey(nodeType))
  57. {
  58. throw new KeyNotFoundException($"NodeType没有定义该节点: {nodeType}");
  59. }
  60. return this.dictionary[nodeType](proto);
  61. }
  62. private Node CreateTreeNode(NodeConfig proto)
  63. {
  64. Node node = this.CreateOneNode(proto);
  65. if (proto.Children == null)
  66. {
  67. return node;
  68. }
  69. foreach (NodeConfig nodeProto in proto.Children)
  70. {
  71. Node childNode = this.CreateTreeNode(nodeProto);
  72. node.AddChild(childNode);
  73. }
  74. return node;
  75. }
  76. private BehaviorTree CreateTree(TreeConfig treeConfig)
  77. {
  78. Node node = this.CreateTreeNode(treeConfig.Root);
  79. return new BehaviorTree(node);
  80. }
  81. }
  82. }