unity 暂停按钮_Unity通过按钮控制视频播放与停止

1. 创建Canvas--RawImage。

2. 导入视频资源(在Assets目录下新建Video文件夹),直接将视频拖入Video文件夹。

3. 将导入的视频拖入第1步新建的RawImage,RawImage右边的Inspector栏将自动出现Video Player。

将导入的视频拖入Video Clip。

4. 创建按钮Button,text改成  暂停。

5. 创建C#脚本Movie,控制视频播放与暂停。脚本如下:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.Video;

using UnityEngine.UI;

public class Movie : MonoBehaviour

{

public Text text_PlayOrPause;

public Button button_PlayOrPause;

private VideoPlayer videoPlayer;

private RawImage rawImage;

private int flag = 0;

//private AudioSource audioSource;

// Start is called before the first frame update

void Start()

{

videoPlayer = this.GetComponent();

//audioSource = this.GetComponent();

rawImage = this.GetComponent();

button_PlayOrPause.onClick.AddListener(PlayorPause);

}

void Update()

{

//判断视频播放情况,播放则按钮显示暂停,暂停就显示播放,并更新相关文本

//没有视频则返回,不播放

if (flag == 0)

{

if (videoPlayer.texture == null)

{

return;

}

//渲染视频到UGUI

else

{

rawImage.texture = videoPlayer.texture;

flag++;

}

}

}

void PlayorPause()

{

if (videoPlayer.isPlaying == true)

{

videoPlayer.Pause();

//audioSource.Pause();

text_PlayOrPause.text = "播放";

}

else

{

videoPlayer.Play();

//audioSource.Play();

text_PlayOrPause.text = "暂停";

}

}

}

6. 将脚本挂载到Canvas--RawImage并设置相关参数,将第4步创建的Button拖入Button_Play Or Pause,Button下的Text拖入Text_Play Or Pause,如下图。

7. 运行。

你可能感兴趣的:(unity,暂停按钮)