Wait.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using UnityEngine;
  2. namespace BehaviorDesigner.Runtime.Tasks
  3. {
  4. [TaskDescription("Wait a specified amount of time. The task will return running until the task is done waiting. It will return success after the wait time has elapsed.")]
  5. [TaskIcon("{SkinColor}WaitIcon.png")]
  6. public class Wait : Action
  7. {
  8. [Tooltip("The amount of time to wait")]
  9. public SharedFloat waitTime = 1;
  10. [Tooltip("Should the wait be randomized?")]
  11. public SharedBool randomWait = false;
  12. [Tooltip("The minimum wait time if random wait is enabled")]
  13. public SharedFloat randomWaitMin = 1;
  14. [Tooltip("The maximum wait time if random wait is enabled")]
  15. public SharedFloat randomWaitMax = 1;
  16. // The time to wait
  17. private float waitDuration;
  18. // The time that the task started to wait.
  19. private float startTime;
  20. // Remember the time that the task is paused so the time paused doesn't contribute to the wait time.
  21. private float pauseTime;
  22. public override void OnStart()
  23. {
  24. // Remember the start time.
  25. startTime = Time.time;
  26. if (randomWait.Value) {
  27. waitDuration = Random.Range(randomWaitMin.Value, randomWaitMax.Value);
  28. } else {
  29. waitDuration = waitTime.Value;
  30. }
  31. }
  32. public override TaskStatus OnUpdate()
  33. {
  34. // The task is done waiting if the time waitDuration has elapsed since the task was started.
  35. if (startTime + waitDuration < Time.time) {
  36. return TaskStatus.Success;
  37. }
  38. // Otherwise we are still waiting.
  39. return TaskStatus.Running;
  40. }
  41. public override void OnPause(bool paused)
  42. {
  43. if (paused) {
  44. // Remember the time that the behavior was paused.
  45. pauseTime = Time.time;
  46. } else {
  47. // Add the difference between Time.time and pauseTime to figure out a new start time.
  48. startTime += (Time.time - pauseTime);
  49. }
  50. }
  51. public override void OnReset()
  52. {
  53. // Reset the public properties back to their original values
  54. waitTime = 1;
  55. randomWait = false;
  56. randomWaitMin = 1;
  57. randomWaitMax = 1;
  58. }
  59. }
  60. }