2026-06-24 02:33:48 +08:00
|
|
|
using UnityEngine;
|
|
|
|
|
using UnityEngine.UI;
|
|
|
|
|
using UnityEngine.Video;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 画中画视频控制器:用 VideoPlayer 渲染到 RenderTexture,再赋给 RawImage。
|
|
|
|
|
/// 挂在包含 RawImage 和 VideoPlayer 的 GameObject 上。
|
|
|
|
|
/// </summary>
|
|
|
|
|
[RequireComponent(typeof(RawImage))]
|
|
|
|
|
public class VideoController : MonoBehaviour
|
|
|
|
|
{
|
|
|
|
|
[SerializeField] private VideoPlayer _videoPlayer;
|
|
|
|
|
[SerializeField] private RawImage _rawImage;
|
|
|
|
|
|
|
|
|
|
private RenderTexture _renderTexture;
|
|
|
|
|
private bool _isPlaying;
|
|
|
|
|
|
|
|
|
|
private void Awake()
|
|
|
|
|
{
|
|
|
|
|
if (_rawImage == null) _rawImage = GetComponent<RawImage>();
|
|
|
|
|
if (_videoPlayer == null) _videoPlayer = GetComponentInChildren<VideoPlayer>();
|
|
|
|
|
|
|
|
|
|
if (_videoPlayer != null)
|
|
|
|
|
{
|
2026-07-10 03:50:39 +08:00
|
|
|
_videoPlayer.isLooping = true;
|
2026-06-24 02:33:48 +08:00
|
|
|
_videoPlayer.loopPointReached += OnVideoEnd;
|
|
|
|
|
}
|
2026-07-10 03:50:39 +08:00
|
|
|
|
|
|
|
|
// 初始隐藏视频面板
|
|
|
|
|
gameObject.SetActive(false);
|
2026-06-24 02:33:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>播放指定视频文件(StreamingAssets/Videos/ 下)</summary>
|
|
|
|
|
public void PlayVideo(string fileName)
|
|
|
|
|
{
|
|
|
|
|
if (_videoPlayer == null) return;
|
|
|
|
|
|
|
|
|
|
string path = System.IO.Path.Combine(Application.streamingAssetsPath, "Videos", fileName);
|
|
|
|
|
_videoPlayer.url = path;
|
|
|
|
|
|
|
|
|
|
// 创建 RenderTexture
|
|
|
|
|
if (_renderTexture == null)
|
|
|
|
|
{
|
|
|
|
|
int w = _videoPlayer.targetTexture != null ? _videoPlayer.targetTexture.width : 640;
|
|
|
|
|
int h = _videoPlayer.targetTexture != null ? _videoPlayer.targetTexture.height : 360;
|
|
|
|
|
_renderTexture = new RenderTexture(w, h, 0);
|
|
|
|
|
_videoPlayer.targetTexture = _renderTexture;
|
|
|
|
|
if (_rawImage != null) _rawImage.texture = _renderTexture;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_videoPlayer.Play();
|
|
|
|
|
_isPlaying = true;
|
|
|
|
|
gameObject.SetActive(true);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void StopVideo()
|
|
|
|
|
{
|
|
|
|
|
if (_videoPlayer != null) _videoPlayer.Stop();
|
|
|
|
|
_isPlaying = false;
|
|
|
|
|
gameObject.SetActive(false);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void PauseVideo()
|
|
|
|
|
{
|
|
|
|
|
if (_videoPlayer != null) _videoPlayer.Pause();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void ResumeVideo()
|
|
|
|
|
{
|
|
|
|
|
if (_videoPlayer != null) _videoPlayer.Play();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void OnVideoEnd(VideoPlayer vp)
|
|
|
|
|
{
|
|
|
|
|
// 真人演示视频播完自动循环
|
|
|
|
|
vp.Play();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void OnDestroy()
|
|
|
|
|
{
|
|
|
|
|
if (_renderTexture != null)
|
|
|
|
|
{
|
|
|
|
|
_renderTexture.Release();
|
|
|
|
|
Destroy(_renderTexture);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|