【unity】代码控制timeline的暂停与播放

实现功能:
timeline的暂停与播放
视频地址:https://www.bilibili.com/video/bv1PT4y1E7np

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;

public class Timeline_manager_test : MonoBehaviour
{
    private PlayableDirector director = null;
    private TimelineUnit helper = null;
    private ModelBase_test modelbase;
    private GameObject button_next;

    private float[] timeBlock_1;//存放暂停时间的数组
    private float[] currentTimeBlock;
    private int currentIndex;
    private int buttonID;
    private int maxIndex;//timeline的最大分段数

    private void Awake()
    {
        timeBlock_1 = new float[] { 1.5f, 3.5f,5.0f, 8.5f };//暂停时间
        director = GetComponent<PlayableDirector>();
        button_next = GameObject.Find("Canvas/next");//找到next按钮
        button_next.SetActive(false);//先将next按钮隐藏
        if (director == null) {
            director = gameObject.AddComponent<PlayableDirector>();
        }
        helper = new TimelineUnit();
        helper.Init("timeline",director);//存放制作好的timeline
        modelbase = GameObject.Find("Directional Light").GetComponent<ModelBase_test>();
    }
    void Start()
    {
        
    }

    public void Changetimeline() {
        helper.Switch("test");
        helper.SetBinding("Animation Track", modelbase.worker_stand);
        helper.SetBinding("Animation Track1", modelbase.worker_stand);
        director.time = 0.0;//将时间置零
        currentIndex = 0;
        buttonID = 0;
        maxIndex = 3;
        currentTimeBlock = timeBlock_1;
        button_next.SetActive(true);//显示next按钮
        helper.Play();
    }
    // Update is called once per frame
    private void Update()
    {
        if (currentTimeBlock == null) return;
        if (director.state.ToString() == "Playing")
        {
            if (TimeEqual((float)director.time, currentTimeBlock[currentIndex]))
            {
                helper.pause();//暂停timeline
            }
        }
        if (currentIndex == maxIndex && director.state.ToString() == "Paused") {
            button_next.SetActive(false);//播放完整条timeline时隐藏next按钮防止数组索引超出报错
        }

    }

    public bool TimeEqual(float currentTime, float timeBlock)
    {//匹配暂停时间,返回true或者false
        if (currentTime > timeBlock - 0.05f && currentTime < timeBlock + 0.05f)
        {
            return true;
        }
        return false;
    }

    public void ButtonClick()
    {//点击next时继续播放timeline
        if (buttonID == currentIndex && director.state.ToString() == "Paused")
        {
            buttonID++;
            currentIndex++;
            helper.Play();

        }
    }
}

  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值