109 lines
2.9 KiB
C#
109 lines
2.9 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.Video;
|
|
|
|
public class VideoPlayerPool
|
|
{
|
|
private static VideoPlayerPool _instance;
|
|
public static VideoPlayerPool Instance => _instance ??= new VideoPlayerPool();
|
|
|
|
private readonly Queue<VideoPlayer> pool = new Queue<VideoPlayer>();
|
|
private GameObject parent;
|
|
private int maxCount = 5;
|
|
|
|
// 已经分配出去的播放器(方便管理)
|
|
private readonly HashSet<VideoPlayer> inUsePlayers = new HashSet<VideoPlayer>();
|
|
|
|
private VideoPlayerPool()
|
|
{
|
|
}
|
|
|
|
public void Init(GameObject parentObj, int maxPoolCount)
|
|
{
|
|
parent = parentObj;
|
|
maxCount = maxPoolCount;
|
|
|
|
// 先清理旧的
|
|
foreach (var player in pool)
|
|
{
|
|
if (player != null) GameObject.Destroy(player.gameObject);
|
|
}
|
|
|
|
pool.Clear();
|
|
inUsePlayers.Clear();
|
|
|
|
// 创建初始播放器
|
|
for (int i = 0; i < maxCount; i++)
|
|
{
|
|
var go = new GameObject($"VideoPlayer_{i}");
|
|
go.transform.SetParent(parent.transform);
|
|
var player = go.AddComponent<VideoPlayer>();
|
|
|
|
player.playOnAwake = false;
|
|
player.renderMode = VideoRenderMode.RenderTexture;
|
|
|
|
pool.Enqueue(player);
|
|
}
|
|
}
|
|
|
|
// 获取播放器
|
|
public VideoPlayer GetPlayer()
|
|
{
|
|
Debug.Log($"[VideoPlayerPool] GetPlayer VideoPlayerPool===={pool.Count}");
|
|
|
|
if (pool.Count == 0)
|
|
{
|
|
Debug.LogWarning("VideoPlayerPool空了,无法分配更多播放器");
|
|
return null;
|
|
}
|
|
|
|
var player = pool.Dequeue();
|
|
inUsePlayers.Add(player);
|
|
player.gameObject.SetActive(true);
|
|
return player;
|
|
}
|
|
|
|
// 归还播放器
|
|
public void ReturnPlayer(VideoPlayer player)
|
|
{
|
|
if (player == null) return;
|
|
|
|
if (inUsePlayers.Contains(player))
|
|
{
|
|
player.Stop();
|
|
player.clip = null;
|
|
|
|
if (player.targetTexture != null)
|
|
{
|
|
player.targetTexture.Release();
|
|
GameObject.Destroy(player.targetTexture);
|
|
player.targetTexture = null;
|
|
}
|
|
|
|
player.gameObject.SetActive(false);
|
|
inUsePlayers.Remove(player);
|
|
pool.Enqueue(player);
|
|
}
|
|
else
|
|
{
|
|
Debug.LogWarning("尝试归还未被分配的播放器");
|
|
}
|
|
}
|
|
|
|
// 释放所有
|
|
public void DisposeAll()
|
|
{
|
|
foreach (var player in pool)
|
|
{
|
|
if (player != null) GameObject.Destroy(player.gameObject);
|
|
}
|
|
|
|
foreach (var player in inUsePlayers)
|
|
{
|
|
if (player != null) GameObject.Destroy(player.gameObject);
|
|
}
|
|
|
|
pool.Clear();
|
|
inUsePlayers.Clear();
|
|
}
|
|
} |