StartBehaviorTree.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using UnityEngine;
  2. namespace BehaviorDesigner.Runtime.Tasks
  3. {
  4. [TaskDescription("Start a new behavior tree and return success after it has been started.")]
  5. [TaskIcon("{SkinColor}StartBehaviorTreeIcon.png")]
  6. public class StartBehaviorTree : Action
  7. {
  8. [Tooltip("The GameObject of the behavior tree that should be started. If null use the current behavior")]
  9. public SharedGameObject behaviorGameObject;
  10. [Tooltip("The group of the behavior tree that should be started")]
  11. public SharedInt group;
  12. [Tooltip("Should this task wait for the behavior tree to complete?")]
  13. public SharedBool waitForCompletion = false;
  14. [Tooltip("Should the variables be synchronized?")]
  15. public SharedBool synchronizeVariables;
  16. private bool behaviorComplete;
  17. private Behavior behavior;
  18. public override void OnStart()
  19. {
  20. var behaviorTrees = GetDefaultGameObject(behaviorGameObject.Value).GetComponents<Behavior>();
  21. if (behaviorTrees.Length == 1) {
  22. behavior = behaviorTrees[0];
  23. } else if (behaviorTrees.Length > 1) {
  24. for (int i = 0; i < behaviorTrees.Length; ++i) {
  25. if (behaviorTrees[i].Group == group.Value) {
  26. behavior = behaviorTrees[i];
  27. break;
  28. }
  29. }
  30. // If the group can't be found then use the first behavior tree
  31. if (behavior == null) {
  32. behavior = behaviorTrees[0];
  33. }
  34. }
  35. if (behavior != null) {
  36. var variables = Owner.GetAllVariables();
  37. if (variables != null && synchronizeVariables.Value) {
  38. for (int i = 0; i < variables.Count; ++i) {
  39. behavior.SetVariableValue(variables[i].Name, variables[i]);
  40. }
  41. }
  42. behavior.EnableBehavior();
  43. if (waitForCompletion.Value) {
  44. behaviorComplete = false;
  45. behavior.OnBehaviorEnd += BehaviorEnded;
  46. }
  47. }
  48. }
  49. public override TaskStatus OnUpdate()
  50. {
  51. if (behavior == null) {
  52. return TaskStatus.Failure;
  53. }
  54. // Return a status of running if we are waiting for the behavior tree to end and it hasn't ended yet
  55. if (waitForCompletion.Value && !behaviorComplete) {
  56. return TaskStatus.Running;
  57. }
  58. return TaskStatus.Success;
  59. }
  60. private void BehaviorEnded(Behavior behavior)
  61. {
  62. behaviorComplete = true;
  63. }
  64. public override void OnEnd()
  65. {
  66. if (behavior != null && waitForCompletion.Value) {
  67. behavior.OnBehaviorEnd -= BehaviorEnded;
  68. }
  69. }
  70. public override void OnReset()
  71. {
  72. // Reset the properties back to their original values.
  73. behaviorGameObject = null;
  74. group = 0;
  75. waitForCompletion = false;
  76. synchronizeVariables = false;
  77. }
  78. }
  79. }