Files
CC-Framework.Commercialization/Runtime/ADAggregator/AsyncAdPlayer.cs
2026-04-22 20:58:58 +08:00

162 lines
4.6 KiB
C#

using System;
using UnityEngine;
namespace Runtime.ADAggregator
{
public class AsyncAdPlayer
{
private Action<bool> _callback;
private ADPlayer _adPlayer;
private bool firstLoad;
private bool isKill;
private bool isUpdate;
private int loadAttempts;
private float nextLoadRetryTime;
private AdTimeHandler overHandler;
private string _Ad_scene;
private float _outTime;
public AsyncAdPlayer(ADPlayer player , string adScene, Action<bool> callback)
{
this._Ad_scene = adScene;
this._outTime = 0;
this._callback = callback;
this.isKill = false;
this.firstLoad = true;
this.loadAttempts = 0;
this.nextLoadRetryTime = 0f;
this._adPlayer = player;
if (_adPlayer == null)
{
#if UNITY_EDITOR
Debug.LogError("无法播放指定的广告");
#endif
_callback?.Invoke(false);
Kill();
return;
}
ADManager.Instance.OpenMask();
_adPlayer.OnErrorAction = OnError;
_adPlayer.AdScene = this._Ad_scene;
_adPlayer.OnPlayRequestStarted();
isUpdate = true;
ADManager.Instance.AddUpdater(DoUpdate);
}
private void OnError()
{
#if UNITY_EDITOR
Debug.LogError("广告异常: " + this._adPlayer.Key);
#endif
// return;
// if (isUpdate)
// {
// isUpdate = false;
// ADManager.Instance.RemoveUpdater(DoUpdate);
// }
// ADManager.Instance.CloseMask();
// _callback?.Invoke(false);
// Clear();
}
private void DoUpdate()
{
if (!isUpdate)
return;
_outTime += Time.deltaTime;
var callback = _callback;
if (this._outTime >= 15)
{
callback?.Invoke(false);
Kill();
return;
}
if (_adPlayer.IsReadly())
{
#if UNITY_EDITOR
Debug.LogError("开始播放广告: " + this._adPlayer.Key);
#endif
_adPlayer.ShowAD(OnCloseAD, OnComplete);
if (_adPlayer.ADType != AD_Type.AwardVideo)
{
ADManager.Instance.CloseMask();
}
isUpdate = false;
ADManager.Instance.RemoveUpdater(DoUpdate);
}
else if(!_adPlayer.IsLoading())
{
if (loadAttempts < _adPlayer.MaxLoadAttempts)
{
if (this._outTime < nextLoadRetryTime)
{
return;
}
#if UNITY_EDITOR
Debug.LogError("开始加载广告: " + this._adPlayer.Key);
#endif
_adPlayer.LoadAD();
loadAttempts++;
firstLoad = false;
nextLoadRetryTime = this._outTime + _adPlayer.LoadRetryDelaySeconds;
}
else
{
callback?.Invoke(false);
Kill();
}
}
}
private void OnCloseAD()
{
#if UNITY_EDITOR
Debug.LogError("关闭广告: " + this._adPlayer.Key);
#endif
if (overHandler == null)
{
overHandler = ADManager.Instance.CreateTimer(1.5f, () =>
{
this._callback?.Invoke(false);
Clear();
});
}
}
private void OnComplete(bool obj)
{
this.overHandler?.Kill();
this.overHandler = ADManager.Instance.CreateTimer(0.05f, () =>
{
if (_adPlayer != null && _adPlayer.ADType == AD_Type.AwardVideo)
{
ADManager.Instance.OnVideoComplete(obj);
}
_callback?.Invoke(obj);
Clear();
});
}
//销毁广告
public void Kill()
{
if (isKill)
return;
ADManager.Instance.RemoveUpdater(DoUpdate);
Clear();
}
private void Clear()
{
ADManager.Instance.CloseMask();
isKill = true;
_callback = null;
_adPlayer = null;
this.overHandler = null;
}
}
}