65 lines
2.0 KiB
C#
65 lines
2.0 KiB
C#
#if INVECTOR_PLAYABLESANIMATOR
|
|
using System.Collections.Generic;
|
|
using InvectorCore.Playables;
|
|
using UnityEngine;
|
|
|
|
namespace Invector
|
|
{
|
|
/// <summary>
|
|
/// PlayablesAnimator counterpart of <see cref="vTriggerSoundByState"/>. Plays one of
|
|
/// <see cref="sounds"/> when the state crosses <see cref="triggerTime"/>, re-arming per loop.
|
|
/// </summary>
|
|
public class vTriggerSoundByStatePDM : PlayablesStateBehaviour
|
|
{
|
|
public GameObject audioSource;
|
|
public List<AudioClip> sounds;
|
|
public float triggerTime;
|
|
|
|
[System.NonSerialized] private vFisherYatesRandom _random;
|
|
[System.NonSerialized] private bool isTrigger;
|
|
|
|
public override void OnStateEnter(in PlayablesStateContext context)
|
|
{
|
|
isTrigger = false;
|
|
}
|
|
|
|
public override void OnStateUpdate(in PlayablesStateContext context)
|
|
{
|
|
float normalizedTime = context.normalizedTime % 1f;
|
|
|
|
if (normalizedTime >= triggerTime && !isTrigger)
|
|
TriggerSound(context);
|
|
else if (normalizedTime < triggerTime && isTrigger)
|
|
isTrigger = false;
|
|
}
|
|
|
|
private void TriggerSound(in PlayablesStateContext context)
|
|
{
|
|
if (context.Animator == null || sounds == null || sounds.Count == 0)
|
|
return;
|
|
|
|
_random ??= new vFisherYatesRandom();
|
|
isTrigger = true;
|
|
|
|
Vector3 position = context.Animator.transform.position;
|
|
GameObject audioObject;
|
|
if (audioSource != null)
|
|
{
|
|
audioObject = Instantiate(audioSource, position, Quaternion.identity);
|
|
}
|
|
else
|
|
{
|
|
audioObject = new GameObject("audioObject");
|
|
audioObject.transform.position = position;
|
|
}
|
|
|
|
AudioSource source = audioObject.GetComponent<AudioSource>();
|
|
if (source == null)
|
|
return;
|
|
|
|
source.PlayOneShot(sounds[_random.Next(sounds.Count)]);
|
|
}
|
|
}
|
|
}
|
|
#endif
|