前置設定
新增 Render Texture
- 在 Textures 資料夾 右鍵 > Create > Render Texture。
- 修改 Render Texture 的 Size 為 1920 x 1080。
新增 Video Player
- 在場景中 右鍵 > Video > Video Player。
- 拖曳要播放的影片到 Video Clip。
- 取消勾選 Play On Awake。
- 拖曳 Render Texture 到 Target Texture。
新增 Raw Image
- 修改 Game View 的解析度為 1920 x 1080。
- 在場景中 右鍵 > UI > Raw Image。
- 點擊 Raw Image 左上角的 Anchor Present。
- 按住 Alt 點擊 Anchor Present 的 右下角選項,讓 Raw Image 放大至全螢幕。
- 點擊 Scene View 的 2D,開啟 2D 模式。
- 拖曳 Render Texture 到 Raw Image 的 Texture。
新增 C# 腳本
- 在 Scripts 資料夾 右鍵 Create > C# Script 新增腳本,取名為 VideoController。
- 拖曳 VideoController 到 Video Player 之下,到這裡我們已完成所有前置設定。
語法範例
單次播放一部影片
在專案開始執行時播放影片。
1using UnityEngine;
2using UnityEngine.Video;
3
4public class VideoController : MonoBehaviour
5{
6 private VideoPlayer _videoPlayer;
7
8 private void Awake() => _videoPlayer = GetComponent<VideoPlayer>();
9
10 private void Start()
11 {
12 _videoPlayer.Play();
13 }
14}
循環播放一部影片
在專案開始執行時播放影片,當影片播放完畢時自動重播。
1using UnityEngine;
2using UnityEngine.Video;
3
4public class VideoController : MonoBehaviour
5{
6 private VideoPlayer _videoPlayer;
7
8 private void Awake() => _videoPlayer = GetComponent<VideoPlayer>();
9
10 private void Start()
11 {
12 _videoPlayer.isLooping = true;
13 _videoPlayer.Play();
14 }
15}
單次播放多部影片
在專案開始執行時播放第一部影片,當影片播放完畢時自動播放下一部影片,直到 Clips 內的影片全部播完。
1using UnityEngine;
2using UnityEngine.Video;
3
4public class VideoController : MonoBehaviour
5{
6 public VideoClip[] Clips;
7
8 private VideoPlayer _videoPlayer;
9 private int _videoIndex;
10
11 private void Awake() => _videoPlayer = GetComponent<VideoPlayer>();
12
13 private void Start()
14 {
15 _videoIndex = 0;
16 _videoPlayer.clip = Clips[0];
17 _videoPlayer.loopPointReached += NextVideo;
18 _videoPlayer.Play();
19 }
20
21 private void NextVideo(VideoPlayer _)
22 {
23 _videoIndex++;
24 if (_videoIndex >= Clips.Length)
25 {
26 return;
27 }
28
29 _videoPlayer.clip = Clips[_videoIndex];
30 _videoPlayer.Play();
31 }
32}
循環播放多部影片
在專案開始執行時播放第一部影片,當影片播放完畢時自動播放下一部影片。如果 Clips 內的影片全部播完時,將從第一部影片重新播放,無限循環。
1using UnityEngine;
2using UnityEngine.Video;
3
4public class VideoController : MonoBehaviour
5{
6 public VideoClip[] Clips;
7
8 private VideoPlayer _videoPlayer;
9 private int _videoIndex;
10
11 private void Awake() => _videoPlayer = GetComponent<VideoPlayer>();
12
13 private void Start()
14 {
15 _videoIndex = 0;
16 _videoPlayer.clip = Clips[0];
17 _videoPlayer.loopPointReached += NextVideo;
18 _videoPlayer.Play();
19 }
20
21 private void NextVideo(VideoPlayer _)
22 {
23 _videoIndex++;
24 if (_videoIndex >= Clips.Length)
25 {
26 _videoIndex = 0;
27 }
28
29 _videoPlayer.clip = Clips[_videoIndex];
30 _videoPlayer.Play();
31 }
32}