modify scripts

This commit is contained in:
2025-10-17 10:59:23 +08:00
parent 9336ed0d6f
commit 4f782a638e
131 changed files with 79880 additions and 3549 deletions

View File

@ -22,10 +22,11 @@ namespace WordsToolkit.Scripts.Services.Ads.AdUnits
public Action<string> OnShown { get; set; }
public Action<string> OnInitialized { get; set; }
public AdUnit(string placementId, AdReference adReference)
public AdUnit(string placementId, AdReference adReference, AdsHandlerBase adsHandler)
{
PlacementId = placementId;
AdReference = adReference;
AdsHandler = adsHandler;
}
public AdsHandlerBase AdsHandler { get; set; }

View File

@ -10,8 +10,14 @@
// // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// // THE SOFTWARE.
#if IRONSOURCE
using Unity.Services.LevelPlay;
#endif
using UnityEngine;
using WordsToolkit.Scripts.Services.Ads.AdUnits;
#if UMP_AVAILABLE
using GoogleMobileAds.Ump.Api;
#endif
namespace WordsToolkit.Scripts.Services.Ads.Networks
{
@ -19,14 +25,42 @@ namespace WordsToolkit.Scripts.Services.Ads.Networks
public class IronsourceAdsHandler : AdsHandlerBase
{
private IAdsListener _listener;
#if IRONSOURCE
private LevelPlayInterstitialAd _interstitialAd;
private LevelPlayRewardedAd _rewardedAd;
#endif
private void Init(string _id)
{
#if IRONSOURCE
IronSource.Agent.setManualLoadRewardedVideo(true);
IronSource.Agent.validateIntegration();
IronSource.Agent.init(_id);
LevelPlay.ValidateIntegration();
// Set consent for LevelPlay
SetConsentStatus();
// Register initialization events
LevelPlay.OnInitSuccess += SdkInitializationCompletedEvent;
LevelPlay.OnInitFailed += SdkInitializationFailedEvent;
LevelPlay.Init(_id);
#endif
}
private void SetConsentStatus()
{
#if IRONSOURCE && UMP_AVAILABLE
bool hasConsent = ConsentInformation.CanRequestAds();
Debug.Log($"LevelPlay consent status: {hasConsent}");
// Set consent for GDPR
LevelPlay.SetConsent(hasConsent);
// For CCPA compliance (optional)
LevelPlay.SetMetaData("do_not_sell", hasConsent ? "false" : "true");
#elif IRONSOURCE
// Default to no consent if UMP not available
LevelPlay.SetConsent(false);
Debug.Log("UMP not available - setting LevelPlay consent to false");
#endif
}
@ -34,78 +68,121 @@ namespace WordsToolkit.Scripts.Services.Ads.Networks
{
_listener = listener;
Debug.Log(_listener);
#if IRONSOURCE
//Add Rewarded Video Events
IronSourceInterstitialEvents.onAdReadyEvent += OnInterstitialAdReady;
IronSourceInterstitialEvents.onAdLoadFailedEvent += InterstitialAdLoadFailedEvent;
IronSourceRewardedVideoEvents.onAdReadyEvent += OnRewardedVideoAdReady;
IronSourceRewardedVideoEvents.onAdLoadFailedEvent += RewardedVideoAdShowFailedEvent;
IronSourceRewardedVideoEvents.onAdRewardedEvent += Rewardeded;
IronSourceEvents.onSdkInitializationCompletedEvent += SdkInitializationCompletedEvent;
#endif
}
#if IRONSOURCE
private void Rewardeded(IronSourcePlacement obj, IronSourceAdInfo ironSourceAdInfo)
private void SdkInitializationCompletedEvent(LevelPlayConfiguration config)
{
Debug.Log("Ironsource Rewardeded");
_listener?.OnAdsShowComplete();
}
private void SdkInitializationCompletedEvent()
{
Debug.Log("Ironsource SdkInitializationCompletedEvent");
Debug.Log("LevelPlay SdkInitializationCompletedEvent");
_listener?.OnAdsInitialized();
}
private void InterstitialAdLoadFailedEvent(IronSourceError obj)
private void SdkInitializationFailedEvent(LevelPlayInitError error)
{
Debug.Log("Ironsource InterstitialAdLoadFailedEvent " + obj.getCode() + " " + obj.getDescription());
Debug.Log($"LevelPlay SdkInitializationFailedEvent: {error}");
_listener?.OnInitFailed();
}
// Interstitial event handlers
private void InterstitialAdLoadedEvent(LevelPlayAdInfo adInfo)
{
Debug.Log("LevelPlay OnInterstitialAdReady");
_listener?.OnAdsLoaded(adInfo.AdUnitId);
}
private void InterstitialAdLoadFailedEvent(LevelPlayAdError error)
{
Debug.Log($"LevelPlay InterstitialAdLoadFailedEvent: {error}");
_listener?.OnAdsLoadFailed();
}
private void RewardedVideoAdShowFailedEvent(IronSourceError obj)
private void InterstitialAdDisplayFailedEvent(LevelPlayAdInfo levelPlayAdInfo, LevelPlayAdError levelPlayAdError)
{
Debug.Log("1" + obj.getCode());
Debug.Log("2" + obj.getDescription());
Debug.Log("Ironsource RewardedVideoAdShowFailedEvent " + obj.getCode() + " " + obj.getDescription());
Debug.Log(_listener);
Debug.Log($"LevelPlay InterstitialAdDisplayFailedEvent: {levelPlayAdError}");
_listener?.OnAdsShowFailed();
LevelPlay.SetPauseGame(false);
}
private void OnRewardedVideoAdReady(IronSourceAdInfo obj)
#if LEVELPLAY8
private void InterstitialAdDisplayFailedEvent(LevelPlayAdDisplayInfoError obj)
{
Debug.Log("Ironsource OnRewardedVideoAdReady");
_listener?.OnAdsLoaded(obj.instanceId);
}
private void OnInterstitialAdReady(IronSourceAdInfo obj)
{
Debug.Log("Ironsource OnInterstitialAdReady");
_listener?.OnAdsLoaded(obj.instanceId);
Debug.Log($"LevelPlay InterstitialAdDisplayFailedEvent: {obj}");
_listener?.OnAdsShowFailed();
LevelPlay.SetPauseGame(false);
}
#endif
// Rewarded video event handlers
private void RewardedAdLoadedEvent(LevelPlayAdInfo adInfo)
{
Debug.Log("LevelPlay OnRewardedVideoAdReady");
_listener?.OnAdsLoaded(adInfo.AdUnitId);
}
private void RewardedAdLoadFailedEvent(LevelPlayAdError error)
{
Debug.Log($"LevelPlay RewardedVideoAdLoadFailedEvent: {error}");
_listener?.OnAdsLoadFailed();
}
private void RewardedAdDisplayFailedEvent(LevelPlayAdInfo levelPlayAdInfo, LevelPlayAdError levelPlayAdError)
{
Debug.Log($"LevelPlay RewardedVideoAdShowFailedEvent: {levelPlayAdError}");
_listener?.OnAdsShowFailed();
LevelPlay.SetPauseGame(false);
}
#if LEVELPLAY8
private void RewardedAdDisplayFailedEvent(LevelPlayAdDisplayInfoError obj)
{
Debug.Log($"LevelPlay RewardedAdDisplayFailedEvent: {obj}");
_listener?.OnAdsShowFailed();
LevelPlay.SetPauseGame(false);
}
#endif
private void RewardedAdRewardedEvent(LevelPlayAdInfo adInfo, LevelPlayReward reward)
{
Debug.Log("LevelPlay Rewarded");
_listener?.OnAdsShowComplete();
LevelPlay.SetPauseGame(false);
}
private void InterstitialDisplayedEvent(LevelPlayAdInfo obj)
{
Debug.Log("LevelPlay InterstitialDisplayedEvent");
_listener?.OnAdsShowStart();
LevelPlay.SetPauseGame(false);
}
#endif
public override void Init(string _id, bool adSettingTestMode, IAdsListener listener)
{
Debug.Log("Ironsource Init");
Debug.Log("LevelPlay Init");
Init(_id);
Debug.Log("Ironsource SetListener");
Debug.Log("LevelPlay SetListener");
SetListener(listener);
}
public override void Show(AdUnit adUnit)
{
#if IRONSOURCE
if (adUnit.AdReference.adType == EAdType.Interstitial)
if (adUnit.AdReference.adType == EAdType.Interstitial && _interstitialAd != null)
{
IronSource.Agent.showInterstitial();
if (_interstitialAd.IsAdReady())
{
_interstitialAd.ShowAd();
LevelPlay.SetPauseGame(true);
}
}
else if (adUnit.AdReference.adType == EAdType.Rewarded)
else if (adUnit.AdReference.adType == EAdType.Rewarded && _rewardedAd != null)
{
IronSource.Agent.showRewardedVideo();
if (_rewardedAd.IsAdReady())
{
_rewardedAd.ShowAd();
LevelPlay.SetPauseGame(true);
}
}
_listener?.Show(adUnit);
@ -117,26 +194,43 @@ namespace WordsToolkit.Scripts.Services.Ads.Networks
#if IRONSOURCE
if (adUnit.AdReference.adType == EAdType.Interstitial)
{
IronSource.Agent.loadInterstitial();
_interstitialAd = new LevelPlayInterstitialAd(adUnit.PlacementId);
_interstitialAd.OnAdLoaded += InterstitialAdLoadedEvent;
_interstitialAd.OnAdDisplayed += InterstitialDisplayedEvent;
_interstitialAd.OnAdLoadFailed += InterstitialAdLoadFailedEvent;
_interstitialAd.OnAdDisplayFailed += InterstitialAdDisplayFailedEvent;
_interstitialAd.LoadAd();
}
else if (adUnit.AdReference.adType == EAdType.Rewarded)
{
IronSource.Agent.loadRewardedVideo();
_rewardedAd = new LevelPlayRewardedAd(adUnit.PlacementId);
_rewardedAd.OnAdLoaded += RewardedAdLoadedEvent;
_rewardedAd.OnAdLoadFailed += RewardedAdLoadFailedEvent;
_rewardedAd.OnAdDisplayFailed += RewardedAdDisplayFailedEvent;
_rewardedAd.OnAdRewarded += RewardedAdRewardedEvent;
_rewardedAd.LoadAd();
}
#endif
}
public override bool IsAvailable(AdUnit adUnit)
{
#if IRONSOURCE
if (adUnit.AdReference.adType == EAdType.Interstitial)
{
return IronSource.Agent.isInterstitialReady();
return _interstitialAd != null && _interstitialAd.IsAdReady();
}
if (adUnit.AdReference.adType == EAdType.Rewarded)
{
return IronSource.Agent.isRewardedVideoAvailable();
return _rewardedAd != null && _rewardedAd.IsAdReady();
}
#endif
return false;

View File

@ -10,6 +10,9 @@
// // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// // THE SOFTWARE.
#if IRONSOURCE
using Unity.Services.LevelPlay;
#endif
using UnityEngine;
using WordsToolkit.Scripts.Services.Ads.AdUnits;
@ -19,65 +22,100 @@ namespace WordsToolkit.Scripts.Services.Ads.Networks
public class IronsourceBannerHandler : AdsHandlerBase
{
private IAdsListener _listener;
#if IRONSOURCE
private LevelPlayBannerAd _bannerAd;
private LevelPlayBannerAd.Config.Builder configBuilder;
#endif
private void Init(string _id)
{
#if IRONSOURCE
IronSource.Agent.validateIntegration();
IronSource.Agent.init(_id);
LevelPlay.ValidateIntegration();
LevelPlay.Init(_id);
#endif
}
private void SetListener(IAdsListener listener)
{
_listener = listener;
#if IRONSOURCE
IronSourceBannerEvents.onAdLoadedEvent += BannerAdLoadedEvent;
IronSourceBannerEvents.onAdLoadFailedEvent += BannerAdLoadFailedEvent;
IronSourceBannerEvents.onAdClickedEvent += BannerAdClickedEvent;
IronSourceBannerEvents.onAdScreenPresentedEvent += BannerAdScreenPresentedEvent;
IronSourceBannerEvents.onAdScreenDismissedEvent += BannerAdScreenDismissedEvent;
IronSourceBannerEvents.onAdLeftApplicationEvent += BannerAdLeftApplicationEvent;
#endif
}
#if IRONSOURCE
private void BannerAdLoadedEvent(IronSourceAdInfo adInfo)
private void BannerAdLoadedEvent(LevelPlayAdInfo adInfo)
{
Debug.Log("IronSource Banner ad loaded");
_listener?.OnAdsLoaded(adInfo.instanceId);
Debug.Log("LevelPlay Banner ad loaded");
_listener?.OnAdsLoaded(adInfo.AdUnitId);
}
private void BannerAdLoadFailedEvent(IronSourceError error)
private void BannerAdLoadFailedEvent(LevelPlayAdError error)
{
Debug.Log($"IronSource Banner ad load failed. Error: {error.getCode()} - {error.getDescription()}");
Debug.Log($"LevelPlay Banner ad load failed. Error: {error}");
_listener?.OnAdsLoadFailed();
}
private void BannerAdClickedEvent(IronSourceAdInfo adInfo)
private void BannerAdClickedEvent(LevelPlayAdInfo adInfo)
{
Debug.Log("IronSource Banner ad clicked");
Debug.Log("LevelPlay Banner ad clicked");
}
private void BannerAdScreenPresentedEvent(IronSourceAdInfo adInfo)
private void BannerAdDisplayedEvent(LevelPlayAdInfo adInfo)
{
Debug.Log("IronSource Banner ad screen presented");
Debug.Log("LevelPlay Banner ad displayed");
}
private void BannerAdScreenDismissedEvent(IronSourceAdInfo adInfo)
private void BannerAdDisplayFailedEvent(LevelPlayAdInfo levelPlayAdInfo, LevelPlayAdError levelPlayAdError)
{
Debug.Log("IronSource Banner ad screen dismissed");
Debug.Log($"LevelPlay Banner ad display failed. Error: {levelPlayAdError}");
}
private void BannerAdLeftApplicationEvent(IronSourceAdInfo adInfo)
#if LEVELPLAY8
private void BannerAdDisplayFailedEvent(LevelPlayAdDisplayInfoError error)
{
Debug.Log("IronSource Banner ad caused app to leave");
Debug.Log($"LevelPlay Banner ad display failed. Error: {error}");
}
#endif
private void BannerAdLeftApplicationEvent(LevelPlayAdInfo adInfo)
{
Debug.Log("LevelPlay Banner ad caused app to leave");
}
private LevelPlayBannerAd GetBannerAd(AdUnit adUnit)
{
configBuilder ??= new LevelPlayBannerAd.Config.Builder();
#if LEVELPLAY9
configBuilder.SetSize(LevelPlayAdSize.BANNER);
#elif LEVELPLAY8
configBuilder.SetSize(com.unity3d.mediation.LevelPlayAdSize.BANNER);
#endif
#if LEVELPLAY9
configBuilder.SetPosition(LevelPlayBannerPosition.BottomCenter);
#elif LEVELPLAY8
configBuilder.SetPosition(com.unity3d.mediation.LevelPlayBannerPosition.BottomCenter);
#endif
configBuilder.SetDisplayOnLoad(true);
#if UNITY_ANDROID
configBuilder.SetRespectSafeArea(true); // Only relevant for Android
#endif
configBuilder.SetPlacementName("bannerPlacement");
configBuilder.SetBidFloor(1.0); // Minimum bid price in USD
var bannerConfig = configBuilder.Build();
var bannerAd = new LevelPlayBannerAd(adUnit.PlacementId, bannerConfig);
bannerAd.OnAdLoaded += BannerAdLoadedEvent;
bannerAd.OnAdLoadFailed += BannerAdLoadFailedEvent;
bannerAd.OnAdClicked += BannerAdClickedEvent;
bannerAd.OnAdDisplayed += BannerAdDisplayedEvent;
bannerAd.OnAdDisplayFailed += BannerAdDisplayFailedEvent;
bannerAd.OnAdLeftApplication += BannerAdLeftApplicationEvent;
return bannerAd;
}
#endif
public override void Init(string _id, bool adSettingTestMode, IAdsListener listener)
{
Debug.Log("IronSource Banner Init");
Debug.Log("LevelPlay Banner Init");
Init(_id);
SetListener(listener);
}
@ -85,22 +123,23 @@ namespace WordsToolkit.Scripts.Services.Ads.Networks
public override void Show(AdUnit adUnit)
{
#if IRONSOURCE
if (adUnit.AdReference.adType == EAdType.Banner)
if (_bannerAd == null)
{
IronSource.Agent.displayBanner();
_bannerAd = GetBannerAd(adUnit);
}
if (adUnit.AdReference.adType == EAdType.Banner && _bannerAd != null)
{
_bannerAd.ShowAd();
_listener?.Show(adUnit);
}
#endif
}
public override void Load(AdUnit adUnit)
{
#if IRONSOURCE
if (adUnit.AdReference.adType == EAdType.Banner)
{
IronSourceBannerSize bannerSize = IronSourceBannerSize.BANNER;
IronSource.Agent.loadBanner(bannerSize, IronSourceBannerPosition.BOTTOM);
}
_bannerAd.LoadAd();
#endif
}
@ -114,9 +153,9 @@ namespace WordsToolkit.Scripts.Services.Ads.Networks
public override void Hide(AdUnit adUnit)
{
#if IRONSOURCE
if (adUnit.AdReference.adType == EAdType.Banner)
if (adUnit.AdReference.adType == EAdType.Banner && _bannerAd != null)
{
IronSource.Agent.hideBanner();
_bannerAd.HideAd();
}
#endif
}

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 655355652c9a644febf26cd1a5869bf4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,33 @@
{
"name": "CandySmith.LevelPlay",
"rootNamespace": "",
"references": [
"GUID:00dd4a7ac8c24c898083910c81898ecc",
"GUID:760a4c7888534400e882b82c5b3fba06"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [
{
"name": "com.unity.services.levelplay",
"expression": "[0.0,9.0)",
"define": "LEVELPLAY8"
},
{
"name": "com.unity.services.levelplay",
"expression": "9.0.0",
"define": "LEVELPLAY9"
},
{
"name": "com.unity.services.levelplay",
"expression": "",
"define": "IRONSOURCE"
}
],
"noEngineReferences": false
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 537e7a60660d24526a2d6a89f5f68492
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -12,7 +12,9 @@
using UnityEngine;
using WordsToolkit.Scripts.Services.Ads.AdUnits;
#if UMP_AVAILABLE
using GoogleMobileAds.Ump.Api;
#endif
namespace WordsToolkit.Scripts.Services.Ads.Networks
{
#if UNITY_ADS
@ -28,10 +30,33 @@ namespace WordsToolkit.Scripts.Services.Ads.Networks
public override void Init(string _id, bool adSettingTestMode, IAdsListener listener)
{
SetConsentStatus();
Advertisement.Initialize(_id, adSettingTestMode, this);
this.listener = listener;
}
private void SetConsentStatus()
{
#if UNITY_ADS && UMP_AVAILABLE
bool hasConsent = ConsentInformation.CanRequestAds();
Debug.Log($"Unity Ads consent status: {hasConsent}");
var consentMetaData = new MetaData("gdpr");
consentMetaData.Set("consent", hasConsent);
Advertisement.SetMetaData(consentMetaData);
var privacyMetaData = new MetaData("privacy");
privacyMetaData.Set("mode", "mixed");
Advertisement.SetMetaData(privacyMetaData);
#elif UNITY_ADS
// Default to no consent if UMP not available
var consentMetaData = new MetaData("gdpr");
consentMetaData.Set("consent", false);
Advertisement.SetMetaData(consentMetaData);
Debug.Log("UMP not available - setting Unity Ads consent to false");
#endif
}
public override void Show(AdUnit adUnit)
{
Advertisement.Show(adUnit.PlacementId, this);

View File

@ -12,14 +12,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using VContainer;
using WordConnectGameToolkit.Scripts.Settings;
using WordsToolkit.Scripts.Popups;
using WordsToolkit.Scripts.Services.Ads;
using WordsToolkit.Scripts.Services.Ads.AdUnits;
using WordsToolkit.Scripts.Services.IAP;
using WordsToolkit.Scripts.Settings;
using WordsToolkit.Scripts.System;
#if UMP_AVAILABLE
using GoogleMobileAds.Ump.Api;
#endif
namespace WordsToolkit.Scripts.Services
{
@ -29,6 +34,8 @@ namespace WordsToolkit.Scripts.Services
private readonly List<AdUnit> adUnits = new();
private readonly Dictionary<AdUnit, IAdLifecycleManager> lifecycleManagers = new();
private EPlatforms platforms;
private bool consentInfoUpdateInProgress = false;
private bool adsInitialized = false;
[Inject]
private GameSettings gameSettings;
@ -38,6 +45,8 @@ namespace WordsToolkit.Scripts.Services
[SerializeField]
private ProductID noAdsProduct;
private InterstitialSettings interstitialSettings;
private AdSetting[] adElements;
private void Awake()
{
@ -45,9 +54,86 @@ namespace WordsToolkit.Scripts.Services
{
return;
}
interstitialSettings = Resources.Load<InterstitialSettings>("Settings/AdsInterstitialSettings");
adElements = Resources.Load<AdsSettings>("Settings/AdsSettings").adProfiles;
StartConsentFlow();
}
private void StartConsentFlow()
{
if (consentInfoUpdateInProgress) return;
consentInfoUpdateInProgress = true;
#if UMP_AVAILABLE && (UNITY_ANDROID || UNITY_IOS)
var request = new ConsentRequestParameters();
if (Debug.isDebugBuild || Application.isEditor)
{
var debugSettings = new ConsentDebugSettings
{
DebugGeography = DebugGeography.EEA
};
var testDeviceIds = new List<string>();
// testDeviceIds.Add("YOUR-TEST-DEVICE-ID-HERE"); // Uncomment and add your device ID if needed
if (testDeviceIds.Count > 0)
{
debugSettings.TestDeviceHashedIds = testDeviceIds;
}
request.ConsentDebugSettings = debugSettings;
}
ConsentInformation.Update(request, OnConsentInfoUpdated);
#else
InitializeAds();
#endif
}
#if UMP_AVAILABLE
private void OnConsentInfoUpdated(FormError consentError)
{
consentInfoUpdateInProgress = false;
if (consentError != null)
{
Debug.LogError($"Consent info update failed: {consentError}");
InitializeAds();
return;
}
ConsentForm.LoadAndShowConsentFormIfRequired(OnConsentFormDismissed);
}
private void OnConsentFormDismissed(FormError formError)
{
if (formError != null)
{
Debug.LogError($"Consent form error: {formError}");
}
if (ConsentInformation.CanRequestAds())
{
InitializeAds();
RefreshBannerAds();
}
else
{
Debug.Log("User denied consent or consent not available");
InitializeAds();
}
}
#endif
private void InitializeAds()
{
if (adsInitialized) return;
adsInitialized = true;
platforms = GetPlatform();
var adElements = Resources.Load<AdsSettings>("Settings/AdsSettings").adProfiles;
foreach (var t in adElements)
{
if (t.platforms == platforms && t.enable)
@ -60,7 +146,7 @@ namespace WordsToolkit.Scripts.Services
adList.Add(t);
foreach (var adElement in t.adElements)
{
var adUnit = new AdUnit(adElement.placementId, adElement.adReference);
var adUnit = new AdUnit(adElement.placementId, adElement.adReference, t.adsHandler);
var lifecycleManager = new AdLifecycleManager(t.adsHandler);
lifecycleManagers[adUnit] = lifecycleManager;
adUnits.Add(adUnit);
@ -119,26 +205,72 @@ namespace WordsToolkit.Scripts.Services
private void OnPopupTrigger(Popup popup, bool open)
{
if (IsNoAdsPurchased())
if (IsNoAdsPurchased() || !CanShowAds())
{
return;
}
// Get current level number
int currentLevel = GameDataManager.GetLevelNum();
// Check interstitial ads using InterstitialSettings
if (interstitialSettings != null && interstitialSettings.interstitials != null)
{
foreach (var interstitialElement in interstitialSettings.interstitials)
{
// Check if this interstitial should trigger based on popup
if (((open && interstitialElement.showOnOpen) || (!open && interstitialElement.showOnClose))
&& popup.GetType() == interstitialElement.popup.GetType())
{
var adUnit = adUnits.Find(i => i.AdReference == interstitialElement.adReference);
if (adUnit == null || !adUnit.IsAvailable())
{
adUnit?.Load();
continue;
}
// Check level conditions
if (!IsLevelConditionMet(currentLevel, interstitialElement))
{
continue;
}
// Find placement ID for frequency tracking
string placementId = GetPlacementIdForAdReference(interstitialElement.adReference);
if (placementId == null) continue;
if (!IsFrequencyConditionMet(placementId, interstitialElement.frequency))
{
continue;
}
adUnit.Show();
adUnit.Load();
IncrementAdFrequency(placementId);
return;
}
}
}
// Handle non-interstitial ads (banners, rewarded) using the original logic
foreach (var ad in adList)
{
foreach (var adElement in ad.adElements)
{
if (adElement.adReference.adType == EAdType.Interstitial)
continue; // Skip interstitials as they're handled above
var adUnit = adUnits.Find(i => i.AdReference == adElement.adReference);
if (!lifecycleManagers[adUnit].IsAvailable(adUnit))
if (!adUnit.IsAvailable())
{
lifecycleManagers[adUnit].Load(adUnit);
adUnit.Load();
continue;
}
if (((open && adElement.popup.showOnOpen) || (!open && adElement.popup.showOnClose)) && popup.GetType() == adElement.popup.popup.GetType())
{
lifecycleManagers[adUnit].Show(adUnit);
lifecycleManagers[adUnit].Load(adUnit);
adUnit.Show();
adUnit.Load();
return;
}
}
@ -152,19 +284,48 @@ namespace WordsToolkit.Scripts.Services
public void ShowAdByType(AdReference adRef, Action<string> shown)
{
if (!gameSettings.enableAds)
if (!gameSettings.enableAds || !CanShowAds())
{
shown?.Invoke(null);
return;
}
int currentLevel = GameDataManager.GetLevelNum();
foreach (var adUnit in adUnits)
{
if (adUnit.AdReference == adRef && lifecycleManagers[adUnit].IsAvailable(adUnit))
if (adUnit.AdReference == adRef && adUnit.IsAvailable())
{
// Check level conditions for interstitial ads using InterstitialSettings
if (adRef.adType == EAdType.Interstitial && interstitialSettings != null)
{
var interstitialElement = interstitialSettings.interstitials?.FirstOrDefault(i => i.adReference == adRef);
if (interstitialElement != null)
{
if (!IsLevelConditionMet(currentLevel, interstitialElement))
{
shown?.Invoke(null);
return;
}
string placementId = GetPlacementIdForAdReference(adRef);
if (placementId != null)
{
if (!IsFrequencyConditionMet(placementId, interstitialElement.frequency))
{
shown?.Invoke(null);
return;
}
// Increment frequency counter
IncrementAdFrequency(placementId);
}
}
}
adUnit.OnShown = shown;
lifecycleManagers[adUnit].Show(adUnit);
lifecycleManagers[adUnit].Load(adUnit);
adUnit.Show();
adUnit.Load();
return;
}
}
@ -193,5 +354,70 @@ namespace WordsToolkit.Scripts.Services
}
}
}
private bool IsLevelConditionMet(int currentLevel, InterstitialAdElement popupSetting)
{
return currentLevel >= popupSetting.minLevel && currentLevel <= popupSetting.maxLevel;
}
private bool IsFrequencyConditionMet(string placementId, int frequency)
{
if (frequency <= 1) return true; // Always show if frequency is 1 or less
int adShowCount = PlayerPrefs.GetInt($"AdCount_{placementId}", 0);
return adShowCount % frequency == 0;
}
private void IncrementAdFrequency(string placementId)
{
int currentCount = PlayerPrefs.GetInt($"AdCount_{placementId}", 0);
PlayerPrefs.SetInt($"AdCount_{placementId}", currentCount + 1);
PlayerPrefs.Save();
}
private string GetPlacementIdForAdReference(AdReference adRef)
{
foreach (var ad in adList)
{
foreach (var adElement in ad.adElements)
{
if (adElement.adReference == adRef)
{
return adElement.placementId;
}
}
}
return null;
}
private bool CanShowAds()
{
#if UMP_AVAILABLE
return ConsentInformation.CanRequestAds();
#else
return true;
#endif
}
public void RefreshBannerAds()
{
if (!CanShowAds() || IsNoAdsPurchased()) return;
foreach (var adUnit in adUnits)
{
if (adUnit.AdReference.adType == EAdType.Banner)
{
lifecycleManagers[adUnit].Show(adUnit);
}
}
}
public void ReconsiderUMPConsent()
{
#if UMP_AVAILABLE && (UNITY_ANDROID || UNITY_IOS)
ConsentInformation.Reset();
#endif
StartConsentFlow();
}
}
}

View File

@ -25,7 +25,6 @@ namespace WordsToolkit.Scripts.Services.IAP
private IExtensionProvider extensionProvider;
public static event Action<string> OnSuccessfulPurchase;
public static event Action<(string,string)> OnFailedPurchase;
public static event Action<bool, List<string>> OnRestorePurchasesFinished;
public void InitializePurchasing(IEnumerable<(string productId, ProductTypeWrapper.ProductType productType)> products)
@ -112,24 +111,20 @@ namespace WordsToolkit.Scripts.Services.IAP
{
Debug.Log(string.Format("Purchasing product asychronously: '{0}'", product.definition.id));
storeController.InitiatePurchase(product);
OnFailedPurchase?.Invoke((productId, "Product not found or not available for purchase.")); // debug only
}
else
{
Debug.Log($"BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase {productId}");
OnFailedPurchase?.Invoke((productId, "InvalidProductID: product not found or not available for purchase."));
}
}
else
{
Debug.Log("IAPInitFailed: BuyProductID FAIL. Not initialized.");
OnFailedPurchase?.Invoke((productId, "IAPInitFailed: Not initialized."));
Debug.Log("BuyProductID FAIL. Not initialized.");
}
}
catch (Exception e)
{
Debug.Log("BuyProductID: FAIL. Exception during purchase. " + e);
OnFailedPurchase?.Invoke((productId, "Exception during purchase: " + e.Message));
}
}
@ -164,13 +159,11 @@ namespace WordsToolkit.Scripts.Services.IAP
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
Debug.Log("OnPurchaseFailed: FAIL. Product: " + product.definition.id + " PurchaseFailureDescription: " + failureDescription);
OnFailedPurchase?.Invoke((product.definition.id, failureDescription.message));
}
public void OnPurchaseFailed(Product i, PurchaseFailureReason p)
{
Debug.Log($"OnPurchaseFailed: FAIL. Product: '{i.definition.id}', PurchaseFailureReason: {p}");
OnFailedPurchase?.Invoke((i.definition.id, p.ToString()));
}
public void OnInitializeFailed(InitializationFailureReason reason)

View File

@ -50,18 +50,12 @@ namespace WordsToolkit.Scripts.Services.IAP
IAPController.OnSuccessfulPurchase += purchaseHandler;
#endif
}
public void SubscribeToPurchaseFailedEvent(Action<(string, string)> purchaseHandler)
{
#if UNITY_PURCHASING
IAPController.OnFailedPurchase += purchaseHandler;
#endif
}
public void UnsubscribeFromPurchaseEvent(Action<string> purchaseHandler)
{
#if UNITY_PURCHASING
#if UNITY_PURCHASING
IAPController.OnSuccessfulPurchase -= purchaseHandler;
#endif
#endif
}
public void BuyProduct(string productId)

View File

@ -13,8 +13,6 @@ namespace WordsToolkit.Scripts.Services.IAP
bool IsProductPurchased(string productId);
void RestorePurchases(Action<bool, List<string>> action);
void SubscribeToPurchaseEvent(Action<string> purchaseHandler);
void SubscribeToPurchaseFailedEvent(Action<(string, string)> purchaseHandler);
void UnsubscribeFromPurchaseEvent(Action<string> purchaseHandler);
}
}

View File

@ -21,5 +21,6 @@ namespace WordsToolkit.Scripts.Services
bool IsRewardedAvailable(AdReference adRef);
void RemoveAds();
bool IsNoAdsPurchased();
void ReconsiderUMPConsent();
}
}