ParallelComplete.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. namespace BehaviorDesigner.Runtime.Tasks
  2. {
  3. [TaskDescription("Similar to the parallel selector task, except the parallel complete task will return the child status as soon as the child returns success or failure." +
  4. "The child tasks are executed simultaneously.")]
  5. [TaskIcon("{SkinColor}ParallelCompleteIcon.png")]
  6. public class ParallelComplete : Composite
  7. {
  8. // The index of the child that is currently running or is about to run.
  9. private int currentChildIndex;
  10. // The task status of every child task.
  11. private TaskStatus[] executionStatus;
  12. public override void OnAwake()
  13. {
  14. // Create a new task status array that will hold the execution status of all of the children tasks.
  15. executionStatus = new TaskStatus[children.Count];
  16. }
  17. public override void OnChildStarted(int childIndex)
  18. {
  19. // One of the children has started to run. Increment the child index and set the current task status of that child to running.
  20. currentChildIndex++;
  21. executionStatus[childIndex] = TaskStatus.Running;
  22. }
  23. public override bool CanRunParallelChildren()
  24. {
  25. // This task can run parallel children.
  26. return true;
  27. }
  28. public override int CurrentChildIndex()
  29. {
  30. return currentChildIndex;
  31. }
  32. public override bool CanExecute()
  33. {
  34. // We can continue executing if we have more children that haven't been started yet.
  35. return currentChildIndex < children.Count;
  36. }
  37. public override void OnChildExecuted(int childIndex, TaskStatus childStatus)
  38. {
  39. // One of the children has finished running. Set the task status.
  40. executionStatus[childIndex] = childStatus;
  41. }
  42. public override void OnConditionalAbort(int childIndex)
  43. {
  44. // Start from the beginning on an abort
  45. currentChildIndex = 0;
  46. for (int i = 0; i < executionStatus.Length; ++i) {
  47. executionStatus[i] = TaskStatus.Inactive;
  48. }
  49. }
  50. public override TaskStatus OverrideStatus(TaskStatus status)
  51. {
  52. if (currentChildIndex == 0) {
  53. return TaskStatus.Success;
  54. }
  55. // Return the child task's status as soon as a child task returns success or failure.
  56. for (int i = 0; i < currentChildIndex; ++i) {
  57. if (executionStatus[i] == TaskStatus.Success || executionStatus[i] == TaskStatus.Failure) {
  58. return executionStatus[i];
  59. }
  60. }
  61. return TaskStatus.Running;
  62. }
  63. public override void OnEnd()
  64. {
  65. // Reset the execution status and the child index back to their starting values.
  66. for (int i = 0; i < executionStatus.Length; ++i) {
  67. executionStatus[i] = TaskStatus.Inactive;
  68. }
  69. currentChildIndex = 0;
  70. }
  71. }
  72. }