Unity Ads 4.0.1多广告单元异常:奖励回调重复触发问题
Unity Ads多激励广告回调冲突问题
我在Unity游戏中接入了两个不同的激励广告:continueAd(观看后可复活)和DoubleRewards(观看后获得双倍资源),二者均绑定在游戏内按钮上。目前遇到的问题是:观看continueAd并获取奖励后,后续观看任意广告都会触发continueAd的奖励逻辑,甚至同时触发两个广告的奖励,疑似Unity Editor存在未清空的回调队列。
最初我的代码完全遵循Unity官方文档实现,为修复该问题,我新增了RewardAdsParent类,尝试在广告播放后销毁组件,下次启用时重建按钮对象,但问题仍未解决。我也尝试过相关的解决方案。
修改后的代码
RewardAdsParent类
public class RewardAdsParent : MonoBehaviour { RewardAdsButton _rewardAdsButton; [SerializeField] Button _showAdButton; [SerializeField] string _androidAdUnitId = "Rewarded_Android"; [SerializeField] string _iOSAdUnitId = "Rewarded_iOS"; private void OnEnable() { if (_rewardAdsButton == null && _showAdButton.enabled) { _rewardAdsButton = _showAdButton.AddComponent<RewardAdsButton>(); _rewardAdsButton.Initialize(_showAdButton, _androidAdUnitId, _iOSAdUnitId, this); _rewardAdsButton.enabled = true; } } private void OnDisable() { PostAdCleanup(); } public void PostAdCleanup() { Destroy(_rewardAdsButton, 0.25f); // 不太喜欢这个延迟,最好等事件触发再销毁 _rewardAdsButton = null; } }
修改后的RewardAdsButton类
public void Initialize(Button showAdButton, string androidAdUnitId, string iOSAdUnitId, RewardAdsParent rewardAdsParent) { this._showAdButton = showAdButton; this._androidAdUnitId = androidAdUnitId; this._iOSAdUnitId = iOSAdUnitId; this.parent = rewardAdsParent; // 获取当前平台的广告单元ID: #if UNITY_IOS _adUnitId = _iOSAdUnitId; #elif UNITY_ANDROID _adUnitId = _androidAdUnitId; #endif if (_showAdButton != null) { // 广告准备好前禁用按钮: _showAdButton.interactable = false; } else { Debug.LogWarning("showAdButton为空"); } if (Advertisement.isInitialized) { LoadAd(); } } void OnDestroy() { // 清理按钮监听器: _showAdButton.onClick.RemoveAllListeners(); } // 实现Show Listener的OnUnityAdsShowComplete回调方法,判断用户是否获得奖励: public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState) { if (adUnitId.Equals(_adUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED)) { Debug.Log("Unity Ads激励广告播放完成"); // 发放奖励 RewardAdHandler.HandleReward(adUnitId); // 加载下一条广告: // Advertisement.Load(_adUnitId, this); parent.PostAdCleanup(); } } // 广告加载成功后,给按钮添加监听器并启用按钮: public void OnUnityAdsAdLoaded(string adUnitId) { Debug.Log("广告加载完成: " + adUnitId); if (adUnitId.Equals(_adUnitId)) { // 设置按钮点击时调用ShowAd()方法: _showAdButton.onClick.AddListener(ShowAd); // 启用按钮允许用户点击: _showAdButton.interactable = true; } } // 实现用户点击按钮时执行的方法: public void ShowAd() { // 禁用按钮: _showAdButton.interactable = false; // 播放广告: Advertisement.Show(_adUnitId, this); }
内容的提问来源于stack exchange,提问作者Jeff
相关产品推荐
相关产品推荐

