PlayOneShot.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using UnityEngine;
  2. namespace BehaviorDesigner.Runtime.Tasks.Unity.UnityAudioSource
  3. {
  4. [TaskCategory("Unity/AudioSource")]
  5. [TaskDescription("Plays an AudioClip, and scales the AudioSource volume by volumeScale. Returns Success.")]
  6. public class PlayOneShot : Action
  7. {
  8. [Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")]
  9. public SharedGameObject targetGameObject;
  10. [Tooltip("The clip being played")]
  11. public SharedObject clip;
  12. [Tooltip("The scale of the volume (0-1)")]
  13. public SharedFloat volumeScale = 1;
  14. private AudioSource audioSource;
  15. private GameObject prevGameObject;
  16. public override void OnStart()
  17. {
  18. var currentGameObject = GetDefaultGameObject(targetGameObject.Value);
  19. if (currentGameObject != prevGameObject) {
  20. audioSource = currentGameObject.GetComponent<AudioSource>();
  21. prevGameObject = currentGameObject;
  22. }
  23. }
  24. public override TaskStatus OnUpdate()
  25. {
  26. if (audioSource == null) {
  27. Debug.LogWarning("AudioSource is null");
  28. return TaskStatus.Failure;
  29. }
  30. audioSource.PlayOneShot((AudioClip)clip.Value, volumeScale.Value);
  31. return TaskStatus.Success;
  32. }
  33. public override void OnReset()
  34. {
  35. targetGameObject = null;
  36. clip = null;
  37. volumeScale = 1;
  38. }
  39. }
  40. }