I am kinda new to Unity and ECS so to avoid the XY problem (https://xyproblem.info) I will add more details about what I am trying to accomplish in the first comment of this post
I found this video (https://youtu.be/nKpM98I7PeM) about behavior trees in Unity and I really liked the concept. I thought about trying to implement it using ECS because it looks very useful for the AI of enemies and an Ability System that I am planning to develop. This is what I basically came up with:
- In the GameObjects implementation each node starts from the abstract
Nodeclass and inherits a few other classes. For example, theDebugLogNodein the video inherits fromActionNodewhich inherits fromNode. Since we can't inherit using structs I decided to separate each of these classes as components. So I have theNode,CompositeNode,SequencerNode, and a few other components. - We can't have duplicated components in the same entity (unless we use a buffer) so to solve this I decided to use one entity for each node in the behavior tree. All entities would have at least the
Nodecomponent then a few more depending on their objective. For example, I have a node that changes the animation of the player so it has theNodeandAnimationNodecomponents - The GameObject implementation is very simple since they are classes and can run methods directly on itself, this makes it easy to keep control of which child node to run. Since I am using ECS I need to use the systems, but behavior trees have a specific execution order so the systems can't run all of them immediately. My solution for this was to change the
Nodecomponent into an enableable component and by default it starts disabled. Then when the node needs to run it is enabled. TheSequencerNodesystem for example, needs to run the children sequentially, so the respective component has an index and the system enables and disables theNodes in the necessary order to execute the behavior tree. Each node has a dedicated system to run their logic
Ok so here are my questions:
- From my research it looks like behavior trees are popular, is there an already existing solution for this? Am I reinventing the wheel?
- Can you see any obvious flaws in my solution? Maybe a performance issue? Since I am new this is a bit hard for me to predict
- Is it an issue that I am creating too many entities for a single behavior tree? Usually they will have at most 20 nodes, so that's roughly 21 entities. I am planning to use it for an Ability System so each time an entity casts an spell all these entities would be created again then shortly after destroyed
I am attaching a sketch that I did when trying to figure out how to implement it, in case it helps to make sense of my big text
I will play a bit with the scriptableobjects and think about a conversion to the structs

