1打开unity,新建一个场景,创建 GameObject-----UI-----RawImage.并且创建三个按钮分别为暂停与播放按钮,上一个,下一个,两个切换按钮。调整好合适的大小和位置。
2.下载好两个以上需要切换的视频,注意修改格式为MP4格式。接下来就导入视频资源。打开unity -----直接将视频拖入Assets界面。
3.编写脚本对视频的播放进行控制。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
public class Video_Controller : MonoBehaviour {
private VideoPlayer videoplayer;
private RawImage rawImage;
private int currentClipIndex;
public Text text_playorpause;
public Button button_playorpause;
public Button button_pre;
public Button button_next;
public VideoClip[] videoClips;//定义了一个数组
// Use this for initialization
void Start () {
videoplayer = this.GetComponent<VideoPlayer>();//获取组件
rawImage = this.GetComponent<RawImage>();
currentClipIndex = 0;
button_playorpause.onClick.AddListener(OnplayorpauseVideo);
button_pre.onClick.AddListener(OnpreVideo);
button_next.onClick.AddListener(OnnextVideo);//调用方法
}
// Update is called once per frame
void Update () {
if (videoplayer.texture == null)
{
return;
}
rawImage.texture = videoplayer.texture;
}
private void OnplayorpauseVideo() {
if (videoplayer.enabled == true)
{
if (videoplayer.isPlaying) {
videoplayer.Pause();
text_playorpause.text = "播放";
Debug.Log("2322");//用于调试脚本不能正常运行
}
else if (!videoplayer.isPlaying)
{
videoplayer.Play();
Debug.Log("111");
text_playorpause.text = "暂停";
}
}
}
private void OnpreVideo() {
currentClipIndex -= 1;
if (currentClipIndex < 0) {
currentClipIndex = videoClips.Length - 1;
}
videoplayer.clip = videoClips[currentClipIndex];
text_playorpause.text = "暂停";
}
private void OnnextVideo()
{
currentClipIndex += 1;
currentClipIndex = currentClipIndex % videoClips.Length;
videoplayer.clip = videoClips[currentClipIndex];
text_playorpause.text = "暂停";
}
}
4.把脚本挂在RawImage上。并给脚本赋予相应的按钮。
最后点击运行就可以实现视频的播放暂停,和切换。
5.思路方法总结:
多个视频播放,要判断视频的播放状态,转化按钮的功能。要实现视频播放和暂停videoplayer.play();和video.pause();的方法;就需要运用到videoplayer.enabled(bool),videoplayer.isplaying或!videoplayer.is playing等的布尔类型来进行判断。
创建一个数组来存储视频。public VideoClip[] video Clips.自定义了暂停与播放,上一个,下一个三个方法。