Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Advice for combining Rewarded and Interstitial

Discussion in 'Unity Mediation' started by nobluff67, May 15, 2023.

  1. nobluff67

    nobluff67

    Joined:
    Nov 3, 2016
    Posts:
    338
    Is there a recommended practice for using these two products from a code pov?

    They both have a lot of duplicate code (e.g. InitializationComplete), so is it best practice to combine the code and make the portions that are specific to each product unique? (e.g. change LoadAd to LoadAdInterstitial and LoadAdRewarded).
     
  2. VirginieC

    VirginieC

    Unity Technologies

    Joined:
    Aug 1, 2019
    Posts:
    17
    Hey nobluff67, what version of the package are you using? :)
     
  3. nobluff67

    nobluff67

    Joined:
    Nov 3, 2016
    Posts:
    338
    1.0.5

    I have not migrated to the ironsource yet as I am nearly ready to launch.

    I have in the meantime combined the code and it seems to have solved an issue that I was experiencing.
     
  4. DeclanMcPartlin

    DeclanMcPartlin

    Unity Technologies

    Joined:
    Nov 19, 2020
    Posts:
    146
    Hello @nobluff67,

    InitializationComplete is not really part of either interstitial or rewarded, this is part of a required step before loading any ad object, the initialization step.

    Regarding combining Rewarded and Interstitial, I'd like to better understand your use case. Could you provide more insight in regards to what you are trying to achieve? Any code snippets to go with it would also help a lot.

    Although the interfaces for these ad types are similar, they are generally used in different contexts within a game. One is mainly used for rewarding the user with something of worth within the context of the game, whereas an interstitial tends to show up between different segments of a game, the end of a level, etc. If you are using both, the lifecycle of each of those ads should be different, meaning the different calls and callbacks you make will very likely be different, potentially in different places.

    Thank you for reaching out!
     
  5. nobluff67

    nobluff67

    Joined:
    Nov 3, 2016
    Posts:
    338
    Here is the code, nothing special as I have just combined the two sample codes. I am using the reward from a menu button in order to reward the user with consumable rewards. The interstitial I am using after each 10 attempts (win or lose counts as an attempt).

    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using Unity.Services.Core;
    4. using Unity.Services.Mediation;
    5.  
    6. public class AdsController : MonoBehaviour
    7. {
    8.     public static AdsController Instance { get; private set; }
    9.  
    10.     [Header("Ad Unit Ids"), Tooltip("Android Ad Unit Ids")]
    11.     public string androidAdUnitIdReward;
    12.     [Tooltip("iOS Ad Unit Ids")] public string iosAdUnitIdReward;
    13.     [Header("Ad Unit Ids"), Tooltip("Android Ad Unit Ids")]
    14.     public string androidAdUnitIdInterstitial;
    15.     [Tooltip("iOS Ad Unit Ids")] public string iosAdUnitIdInterstitial;
    16.  
    17.     [Header("Game Ids"),
    18.      Tooltip("[Optional] Specifies the iOS GameId. Otherwise uses the GameId of the linked project.")]
    19.     public string iosGameId;
    20.  
    21.     [Tooltip("[Optional] Specifies the Android GameId. Otherwise uses the GameId of the linked project.")]
    22.     public string androidGameId;
    23.  
    24.     private bool musicWasOn;
    25.  
    26.     IRewardedAd m_RewardedAd;
    27.     IInterstitialAd m_InterstitialAd;
    28.  
    29.     private void Awake()
    30.     {
    31.         if (Instance == null)
    32.         {
    33.             Instance = this;
    34.         }
    35.         else if (Instance != this)
    36.         {
    37.             Destroy(this);
    38.         }
    39.  
    40. //        DontDestroyOnLoad(this.gameObject);
    41.     }
    42.  
    43.     async void Start()
    44.     {
    45.         try
    46.         {
    47.             await UnityServices.InitializeAsync(GetGameId());
    48.             InitializationComplete();
    49.         }
    50.         catch (Exception e)
    51.         {
    52.             InitializationFailed(e);
    53.         }
    54.     }
    55.  
    56.     void OnDestroy()
    57.     {
    58.         m_RewardedAd?.Dispose();
    59.         m_InterstitialAd?.Dispose();
    60.     }
    61.  
    62.     InitializationOptions GetGameId()
    63.     {
    64.         var initializationOptions = new InitializationOptions();
    65.  
    66. #if UNITY_IOS
    67.                 if (!string.IsNullOrEmpty(iosGameId))
    68.                 {
    69.                     initializationOptions.SetGameId(iosGameId);
    70.                 }
    71. #elif UNITY_ANDROID
    72.         if (!string.IsNullOrEmpty(androidGameId))
    73.         {
    74.             initializationOptions.SetGameId(androidGameId);
    75.         }
    76. #endif
    77.  
    78.         return initializationOptions;
    79.     }
    80.  
    81.  
    82.     public async void ShowRewarded()
    83.     {
    84.         Debug.Log("HEre");
    85.         if (GlobalData.Instance.isMusicOn)
    86.         {
    87.             musicWasOn = true;
    88.             GlobalVars.Instance.asMusic.mute = true;
    89.         }
    90.  
    91.         if (m_RewardedAd?.AdState == AdState.Loaded)
    92.         {
    93.             try
    94.             {
    95.                 var showOptions = new RewardedAdShowOptions {AutoReload = true};
    96.                 await m_RewardedAd.ShowAsync(showOptions);
    97.                 //GlobalData.Instance.temptext.text += "\nreward shown";
    98.                 if (musicWasOn)
    99.                 {
    100.                     GlobalVars.Instance.asMusic.mute = false;
    101.                 }
    102.             }
    103.             catch (ShowFailedException e)
    104.             {
    105.                 Debug.LogWarning($"Rewarded failed to show: {e.Message}");
    106.                 if (musicWasOn)
    107.                 {
    108.                     GlobalVars.Instance.asMusic.mute = false;
    109.                 }
    110.             }
    111.         }
    112.         else
    113.         {
    114.             //GlobalData.Instance.temptext.text += "\nno video: " + m_RewardedAd?.AdState;
    115.             if (musicWasOn)
    116.             {
    117.                 GlobalVars.Instance.asMusic.mute = false;
    118.             }
    119.  
    120.         }
    121.     }
    122.  
    123.     public async void ShowRewardedWithOptions()
    124.     {
    125.         if (m_RewardedAd?.AdState == AdState.Loaded)
    126.         {
    127.             try
    128.             {
    129.                 //Here we provide a user id and custom data for server to server validation.
    130.                 RewardedAdShowOptions showOptions = new RewardedAdShowOptions();
    131.                 showOptions.AutoReload = true;
    132.                 S2SRedeemData s2SData;
    133.                 s2SData.UserId = "my cool user id";
    134.                 s2SData.CustomData = "{\"reward\":\"Gems\",\"amount\":20}";
    135.                 showOptions.S2SData = s2SData;
    136.  
    137.                 await m_RewardedAd.ShowAsync(showOptions);
    138.                 Debug.Log("Rewarded Shown!");
    139.                 if (musicWasOn)
    140.                 {
    141.                     GlobalVars.Instance.asMusic.mute = false;
    142.                 }
    143.             }
    144.             catch (ShowFailedException e)
    145.             {
    146.                 Debug.LogWarning($"Rewarded failed to show: {e.Message}");
    147.                 if (musicWasOn)
    148.                 {
    149.                     GlobalVars.Instance.asMusic.mute = false;
    150.                 }
    151.             }
    152.         }
    153.     }
    154.  
    155.     async void LoadAdReward()
    156.     {
    157.         try
    158.         {
    159.             await m_RewardedAd.LoadAsync();
    160.         }
    161.         catch (LoadFailedException)
    162.         {
    163.             // We will handle the failure in the OnFailedLoad callback
    164.         }
    165.     }
    166.    
    167.     void InitializationComplete()
    168.     {
    169.         MediationService.Instance.ImpressionEventPublisher.OnImpression += ImpressionEvent;
    170.  
    171.         switch (Application.platform)
    172.         {
    173.             case RuntimePlatform.Android:
    174.                 //GlobalData.Instance.temptext.text += "\n android - init reward";
    175.                 m_InterstitialAd = MediationService.Instance.CreateInterstitialAd(androidAdUnitIdInterstitial);
    176.                 m_RewardedAd = MediationService.Instance.CreateRewardedAd(androidAdUnitIdReward);
    177.                 break;
    178.  
    179.             case RuntimePlatform.IPhonePlayer:
    180.                 m_InterstitialAd = MediationService.Instance.CreateInterstitialAd(iosAdUnitIdInterstitial);
    181.                 //GlobalData.Instance.temptext.text += "\n apple - init reward";
    182.                 m_RewardedAd = MediationService.Instance.CreateRewardedAd(iosAdUnitIdReward);
    183.                 break;
    184.             case RuntimePlatform.WindowsEditor:
    185.             case RuntimePlatform.OSXEditor:
    186.             case RuntimePlatform.LinuxEditor:
    187.                 m_InterstitialAd = MediationService.Instance.CreateInterstitialAd(!string.IsNullOrEmpty(androidAdUnitIdInterstitial) ? androidAdUnitIdInterstitial : iosAdUnitIdInterstitial);
    188.                 m_RewardedAd =
    189.                     MediationService.Instance.CreateRewardedAd(!string.IsNullOrEmpty(androidAdUnitIdReward)
    190.                         ? androidAdUnitIdReward
    191.                         : iosAdUnitIdReward);
    192.                 break;
    193.             default:
    194.                 Debug.LogWarning("Mediation service is not available for this platform:" + Application.platform);
    195.                 return;
    196.         }
    197.  
    198.         m_RewardedAd.OnLoaded += AdLoadedReward;
    199.         m_RewardedAd.OnFailedLoad += AdFailedLoadReward;
    200.         m_RewardedAd.OnUserRewarded += UserRewarded;
    201.         m_RewardedAd.OnClosed += AdClosedReward;
    202.        
    203.         m_InterstitialAd.OnLoaded += AdLoadedInterstitial;
    204.         m_InterstitialAd.OnFailedLoad += AdFailedLoadInterstitial;
    205.         m_InterstitialAd.OnClosed += AdClosedInterstitial;
    206.  
    207.         LoadAdReward();
    208.         LoadAdInterstitial();
    209.     }
    210.  
    211.     void InitializationFailed(Exception error)
    212.     {
    213.         SdkInitializationError initializationError = SdkInitializationError.Unknown;
    214.         if (error is InitializeFailedException initializeFailedException)
    215.         {
    216.             initializationError = initializeFailedException.initializationError;
    217.         }
    218.  
    219.         //GlobalData.Instance.temptext.text += "\n - init fail reward";
    220.  
    221.         Debug.Log($"Initialization Failed: {initializationError}:{error.Message}");
    222.     }
    223.  
    224.     void UserRewarded(object sender, RewardEventArgs e)
    225.     {
    226.         MenuSystem.Instance.RewardsCalc("R");
    227.         if (musicWasOn)
    228.         {
    229.             GlobalVars.Instance.asMusic.mute = false;
    230.         }
    231.  
    232.         //Debug.Log($"User Rewarded! Type: {e.Type} Amount: {e.Amount}");
    233.     }
    234.  
    235.     void AdClosedReward(object sender, EventArgs args)
    236.     {
    237.         Debug.Log("Rewarded Closed! Loading Ad...");
    238.         if (musicWasOn)
    239.         {
    240.             GlobalVars.Instance.asMusic.mute = false;
    241.         }
    242.     }
    243.  
    244.     void AdLoadedReward(object sender, EventArgs e)
    245.     {
    246.         //GlobalData.Instance.temptext.text += "\nad loaded - reward";
    247.     }
    248.  
    249.     void AdFailedLoadReward(object sender, LoadErrorEventArgs e)
    250.     {
    251.         //GlobalData.Instance.temptext.text += "\nad failed loaded - reward: " + e.Message;
    252.         Debug.Log(e.Message);
    253.     }
    254.  
    255.     void ImpressionEvent(object sender, ImpressionEventArgs args)
    256.     {
    257.         if (musicWasOn)
    258.         {
    259.             GlobalVars.Instance.asMusic.mute = false;
    260.         }
    261.  
    262.         var impressionData = args.ImpressionData != null ? JsonUtility.ToJson(args.ImpressionData, true) : "null";
    263.     }
    264.  
    265.    
    266.             public async void ShowInterstitial()
    267.         {
    268.             if (GlobalData.Instance.isMusicOn)
    269.             {
    270.                 musicWasOn = true;
    271.                 GlobalVars.Instance.asMusic.mute = true;
    272.             }
    273.  
    274.             if (m_InterstitialAd?.AdState == AdState.Loaded)
    275.             {
    276.                 try
    277.                 {
    278.  
    279.                     var showOptions = new InterstitialAdShowOptions { AutoReload = true };
    280.                     await m_InterstitialAd.ShowAsync(showOptions);
    281. //                    Debug.Log("Interstitial Shown!");
    282.                     if (musicWasOn)
    283.                     {
    284.                         GlobalVars.Instance.asMusic.mute = false;
    285.                     }
    286.                 }
    287.                 catch (ShowFailedException e)
    288.                 {
    289.                     Debug.Log($"Interstitial failed to show : {e.Message}");
    290.                     if (musicWasOn)
    291.                     {
    292.                         GlobalVars.Instance.asMusic.mute = false;
    293.                     }
    294.                 }
    295.             }
    296.             else
    297.             {
    298.                 if (GlobalData.Instance.isMusicOn)
    299.                 {
    300.                     musicWasOn = true;
    301.                     GlobalVars.Instance.asMusic.mute = true;
    302.                 }
    303.             }
    304.         }
    305.  
    306.         async void LoadAdInterstitial()
    307.         {
    308.             try
    309.             {
    310.                 await m_InterstitialAd.LoadAsync();
    311.             }
    312.             catch (LoadFailedException)
    313.             {
    314.                 // We will handle the failure in the OnFailedLoad callback
    315.             }
    316.         }
    317.         void AdClosedInterstitial(object sender, EventArgs args)
    318.         {
    319. //            Debug.Log("Interstitial Closed! Loading Ad...");                  
    320.             if (musicWasOn)
    321.             {
    322.                 GlobalVars.Instance.asMusic.mute = false;
    323.             }
    324.  
    325.         }
    326.  
    327.         void AdLoadedInterstitial(object sender, EventArgs e)
    328.         {
    329.             //GlobalData.Instance.temptext.text += "\nad loaded - inter";
    330.         }
    331.  
    332.         void AdFailedLoadInterstitial(object sender, LoadErrorEventArgs e)
    333.         {
    334.             //GlobalData.Instance.temptext.text += "\nad failed loaded - inter";
    335.             //Debug.Log(e.Message);
    336.         }
    337.  
    338. }
    339.  
    I am using ShowInterstitial and ShowRewarded.

    The issue I was having has been resolved by combining the code.

    The only thing I am not sure about now is what to do when a adload has failed. I am not sure if I should attempt to loadad in the failed event.