// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using UnityEngine;
using UnityEngine.Events;
namespace Microsoft.MixedReality.Toolkit.UI
{
///
/// Add audio clip to play onClick or on Voice Command
///
[AddComponentMenu("Scripts/MRTK/SDK/InteractableAudioReceiver")]
public class InteractableAudioReceiver : ReceiverBase
{
///
/// AudioClip to play when event is selected
///
[InspectorField(Type = InspectorField.FieldTypes.AudioClip, Label = "Audio Clip", Tooltip = "Assign an audioclip to play on click")]
public AudioClip AudioClip;
///
public override bool HideUnityEvents => true;
private State lastState;
///
/// Creates and AudioReceiver, which plays sounds on Click
///
public InteractableAudioReceiver(UnityEvent ev) : base(ev, "AudioEvent")
{
}
///
/// Called on update, check to see if the state has changed sense the last call
///
public override void OnUpdate(InteractableStates state, Interactable source)
{
if (state.CurrentState() != lastState)
{
// the state has changed, do something new
lastState = state.CurrentState();
}
}
///
/// assign the clip to the audio source and play
///
private void PlayAudio(Interactable source)
{
AudioSource audioSource = source.GetComponent();
if (audioSource == null)
{
audioSource = source.gameObject.AddComponent();
}
audioSource.clip = AudioClip;
audioSource.Play();
}
///
/// click happened
///
public override void OnClick(InteractableStates state, Interactable source, IMixedRealityPointer pointer = null)
{
base.OnClick(state, source);
PlayAudio(source);
}
///
/// voice command called
///
public override void OnVoiceCommand(InteractableStates state, Interactable source, string command, int index = 0, int length = 1)
{
base.OnVoiceCommand(state, source, command, index, length);
PlayAudio(source);
}
}
}