-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBehaviorTreeManager.cs
More file actions
116 lines (93 loc) · 3.24 KB
/
BehaviorTreeManager.cs
File metadata and controls
116 lines (93 loc) · 3.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
using System;
using BadTree.BehaviorTree.TreeUpdaters;
using UnityEngine;
namespace BadTree.BehaviorTree {
public enum UpdateMethod {
Update,
FixedUpdate,
Custom,
}
public enum UpdateInterval {
EngineFrame,
ScaledTimeInSeconds,
UnScaledTimeInSeconds,
External, // The user will call Tick by himself
Once,
}
public abstract class BehaviorTreeManager : MonoBehaviour {
[NonSerialized] protected IBtNode root;
[Header("Behavior Base"), SerializeField]
protected bool active;
[SerializeField] protected UpdateMethod updateMethod;
[SerializeField] protected UpdateInterval updateInterval;
[SerializeField] protected float intervalInSeconds;
[SerializeField] protected ICustomUpdater customUpdater;
protected BtResult result;
protected IUpdateHandler Updater { get; set; }
public IBtNode Root => root;
public BtResult Result {
get => result;
set {
result = value;
TriggerEvents(result);
}
}
[field: NonSerialized] public BtEvents Events { get; set; } = new();
private bool Active {
get => active;
set {
active = value;
if (active) {
customUpdater?.SetActive();
} else {
customUpdater?.SetInactive();
}
}
}
public void SetCustomUpdater(ICustomUpdater iCustomUpdater) {
updateMethod = UpdateMethod.Custom;
customUpdater = iCustomUpdater;
}
protected virtual void Build() {
if (Root == null && Active) {
Result = BtResult.Failed;
Debug.LogError($"Activated behavior tree without root");
}
Root?.Init();
Updater = TreeUpdatersFactory.Create(updateMethod, updateInterval, intervalInSeconds);
if (updateMethod == UpdateMethod.Custom) {
customUpdater.SetRoot(root);
customUpdater.SetActive();
customUpdater.OnTickResult += OnCustomTickUpdate;
}
}
protected virtual void Update() {
if (updateMethod != UpdateMethod.Update || !Active) {
return;
}
BtResult btResult = Updater.TryTick((Entry)Root, out bool ticked);
if (ticked) {
Result = btResult;
}
}
protected virtual void FixedUpdate() {
if (updateMethod != UpdateMethod.FixedUpdate || !Active) {
return;
}
BtResult btResult = Updater.TryTick((Entry)Root, out bool ticked);
if (ticked) {
Result = btResult;
}
}
#region Events
private void OnCustomTickUpdate(BtResult cResult) {
if (!active) {
Result = BtResult.Failed;
throw new ApplicationException($"Custom updater has not been deactivated");
}
Result = cResult;
}
private void TriggerEvents(BtResult btResult) { Events.Raise(btResult, root); }
#endregion
}
}