1. 程式人生 > 實用技巧 >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<VideoPlayer>();
        //audioSource = this.GetComponent<AudioSource>();
        rawImage = this.GetComponent<RawImage>();
        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. 執行。