Unity点击按钮控制视频播放和暂停

省流:整体脚本放在底部,需要可直接到底部

1、导入命名空间

using UnityEngine.UI;
using UnityEngine.Video;

2、创建变量

private VideoPlayer videoplayer;
public Button button_playorpause;

3、第一帧开始时调用

videoplayer=this.GetComponent<VideoPlayer>();//获取当前对象上的VideoPlayer组件
button_playorpause.onClick.AddListener(OnplayorpauseVideo);//向按钮事件添加监听器

4、每帧调用

if(videoplayer.texture==null)//检查视频播放器纹理是否为空
{
    return;
}

5、定义方法OnplayorpauseVideo

private void OnplayorpauseVideo()
{
    if(videoplayer.enabled==true)//检查视频播放器是否启用
    {
        if(videoplayer.isPlaying)//判断视频是否播放
        {
            videoplayer.Pause();//视频暂停
        }
        else if(!videoplayer.isPlaying)
        {
            videoplayer.Play();//视频播放
        }
    }
}

6、创建图像,添加视频播放器(Video Player)组件,把脚本放到图像,把按钮添加到脚本。

完整代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

public class Video_Controller : MonoBehaviour
{
    private VideoPlayer videoplayer;
    public Button button_Video;

    // Start is called before the first frame update
    void Start()
    {
        videoplayer = this.GetComponent<VideoPlayer>();
        button_Video.onClick.AddListener(VideoSwitch);
    }

    // Update is called once per frame
    void Update()
    {
        if (videoplayer.texture == null)
        {
            return;
        }
    }

    private void VideoSwitch()
    {
        if (videoplayer.enabled == true)
        {
            if (videoplayer.isPlaying)
            {
                videoplayer.Pause();
            }
            else if (!videoplayer.isPlaying)
            {
                videoplayer.Play();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/clown_sam/article/details/132725435