Play.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #if UNITY_2017_1_OR_NEWER
  2. using UnityEngine;
  3. using UnityEngine.Playables;
  4. namespace BehaviorDesigner.Runtime.Tasks.Unity.Timeline
  5. {
  6. [TaskCategory("Unity/Timeline")]
  7. [TaskDescription("Instatiates a Playable using the provided PlayableAsset and starts playback.")]
  8. public class Play : Action
  9. {
  10. [Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")]
  11. public SharedGameObject targetGameObject;
  12. [Tooltip("An asset to instantiate a playable from.")]
  13. public PlayableAsset playableAsset;
  14. [Tooltip("Should the task be stopped when the timeline has stopped playing?")]
  15. public SharedBool stopWhenComplete;
  16. private PlayableDirector playableDirector;
  17. private GameObject prevGameObject;
  18. private bool playbackStarted;
  19. public override void OnStart()
  20. {
  21. var currentGameObject = GetDefaultGameObject(targetGameObject.Value);
  22. if (currentGameObject != prevGameObject) {
  23. playableDirector = currentGameObject.GetComponent<PlayableDirector>();
  24. prevGameObject = currentGameObject;
  25. }
  26. playbackStarted = false;
  27. }
  28. public override TaskStatus OnUpdate()
  29. {
  30. if (playableDirector == null) {
  31. Debug.LogWarning("PlayableDirector is null");
  32. return TaskStatus.Failure;
  33. }
  34. if (playbackStarted) {
  35. if (stopWhenComplete.Value && playableDirector.state == PlayState.Playing) {
  36. return TaskStatus.Running;
  37. }
  38. return TaskStatus.Success;
  39. }
  40. if (playableAsset == null) {
  41. playableDirector.Play();
  42. } else {
  43. playableDirector.Play(playableAsset);
  44. }
  45. playbackStarted = true;
  46. return stopWhenComplete.Value ? TaskStatus.Running : TaskStatus.Success;
  47. }
  48. public override void OnReset()
  49. {
  50. targetGameObject = null;
  51. playableAsset = null;
  52. stopWhenComplete = false;
  53. }
  54. }
  55. }
  56. #endif