94 lines
1.9 KiB
C#
94 lines
1.9 KiB
C#
using UnityEngine;
|
||
using UnityEngine.Playables;
|
||
using UnityEngine.UI;
|
||
using UnityEngine.EventSystems;
|
||
|
||
public class TimelineSliderController : MonoBehaviour,
|
||
IBeginDragHandler, IEndDragHandler
|
||
{
|
||
[Header("Timeline")]
|
||
public PlayableDirector director;
|
||
|
||
[Header("UI")]
|
||
public Slider slider;
|
||
|
||
private bool isDragging;
|
||
|
||
public Animator[] animators;
|
||
|
||
|
||
public void Freeze()
|
||
{
|
||
foreach (var animator in animators)
|
||
{
|
||
if (animator != null)
|
||
animator.speed = 0f;
|
||
}
|
||
}
|
||
|
||
public void Resume()
|
||
{
|
||
foreach (var animator in animators)
|
||
{
|
||
if (animator != null)
|
||
animator.speed = 1f;
|
||
}
|
||
}
|
||
|
||
void Start()
|
||
{
|
||
if (director == null || slider == null)
|
||
{
|
||
Debug.LogError("TimelineSliderController:引用未设置");
|
||
enabled = false;
|
||
return;
|
||
}
|
||
Freeze();
|
||
// 确保 duration 有值
|
||
director.Evaluate();
|
||
//director.Play();
|
||
slider.minValue = 0f;
|
||
slider.maxValue = (float)director.duration;
|
||
slider.wholeNumbers = false;
|
||
|
||
slider.onValueChanged.AddListener(OnSliderValueChanged);
|
||
}
|
||
|
||
void Update()
|
||
{
|
||
// Timeline → Slider
|
||
if (!isDragging && director.state == PlayState.Playing)
|
||
{
|
||
slider.value = (float)director.time;
|
||
}
|
||
}
|
||
|
||
void OnSliderValueChanged(float value)
|
||
{
|
||
if (!isDragging)
|
||
return;
|
||
|
||
// Slider → Timeline
|
||
director.time = value;
|
||
director.Evaluate();
|
||
|
||
}
|
||
|
||
public void OnBeginDrag(PointerEventData eventData)
|
||
{
|
||
isDragging = true;
|
||
director.Pause();
|
||
Freeze();
|
||
}
|
||
|
||
public void OnEndDrag(PointerEventData eventData)
|
||
{
|
||
isDragging = false;
|
||
|
||
director.time = slider.value;
|
||
director.Evaluate();
|
||
director.Play();
|
||
Resume();
|
||
}
|
||
}
|