Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

Discussion Unity mediation refresh rate and connection interuption handing

Discussion in 'Unity Mediation' started by maxkcy, Sep 16, 2022.

  1. maxkcy

    maxkcy

    Joined:
    Oct 11, 2021
    Posts:
    8
    Hi, I first need to state my ads are initialized by a persistent singleton AdManager GameObject that only calls InitServices(); once in its entire lifetime. Before this, I used an Admanager per level bases. I did not get reconnection issues, because it would just initialize again automatically on scene load.

    Okay, so I am wondering what the refresh rate for mediation is because often I get no fill item (even when I'm using test ads, that's fine though since I am getting test ads nontheless). I would like to know how often ads are fetched, and if there is a way to customize ad fetching/refreshing. 2nd, I want to know how connection interupts are handled. I ended up getting this error for disrupts, and I was unable to get ads in the same session.
    I want to know 2 things about connection interrupts, and how the ads sdk handles the situation;
    • when ads are initialized at the begining when the user has internet turned off, but later during the session the internet is reconnected
    • when internet connection is abruptly lost mid session after initialization, but is reconnected later on
    I tried runing the above senario myself a few times, once the connection is lost, I was unable to reconnect and load new ads. I additionally have questions on how I can customize these behaviors;
    • how to fetch new ads when ads have been shows and no new ad is loaded
    • how to check for internet, and send a call to reconnect if connection was disrupted.
    EDIT: I tested out a few of issues myself and what happens with the default mediation sample code.
    • First issue: what happens when initialization call is made when the internet is not connected? I have a test device that completly disconnects from the internet because when wifi mode is shut off, it doesn't connect to a carrier. The test can also be carried out with airplane mode and wifi on/off conditions. The result was that mediation does not initialize, and will not try to initialize.

    • Second issue: what happens if it is initialized, and the connection is disrupted? Result for the sample code was that it does not try to reconnect. Additionally, once initialized, even after disconnection, a frustrating bug I encountered is that
      Code (CSharp):
      1. UnityServices.State
      returns Initialized.
    • Third issue: What is the ads' refresh rate, is it automatic, and how often it gets called? Result I found that it is only automatically loaded after a successful ad show event is registered. There is no way to customize it.
    • Forth, how can I create custom errors on my own to test out whether my code can handle it? I was unable to find a way to customize the exeception. There is a way, that is when internet is disconnected, to change to my own error type I want to pass to the switch statement, seen later in AdFailedLoad(); but this is still very much hacky, so I did not try it.
    So, the solution I typed up is a bit hacky, but it did seem to solve all the connection and disruption issues, and kept the ads coming consistently. Here it is:

    Code (CSharp):
    1. using System;
    2. using Unity.Services.Core;
    3. using Unity.Services.Mediation;
    4. using UnityEngine;
    5. using UnityEngine.SceneManagement;
    6.  
    7. public class AndroidRewardedAd : MonoBehaviour, IDisposable
    8. {
    9.     [SerializeField] WorkShopManager workShopManager;
    10.     [SerializeField] GameManager gameManager;
    11.     private IRewardedAd ad;
    12.     private string adUnitId = "Rewarded_Android";
    13.     private string gameId = "4444444";
    14.     public bool HasAd;
    15.     int errorLoadingAdCount = 0;
    16.     string adLoadErrorE;
    17.  
    18.     /** This is my own in game script. Most of the code is dirrectly from the sample. The changes are in Awake(); my custom TryInitServices(); InitializationFailed(); AdFailedLoaded(); **/
    19.  
    20.     private void Awake()
    21.     {
    22.  
    23.         TryInitServices();
    24.         InvokeRepeating(nameof(InvokedDebug), 0f, 5f);
    25.     }
    26.  
    27.     private void InvokedDebug() // a quick hacky debug to let me see some the stats
    28.     {
    29.         Debug.Log("AndroidRewardedAd: Connection == " + Application.internetReachability + ". UnityServices.State == " + UnityServices.State +
    30.                   ", HasAd: " + HasAd + ", Sequencial Failed AdLoad Error Count: " + errorLoadingAdCount + "\n Last AdLoadError Message type: " + adLoadErrorE);
    31.     }
    32.     private void OnEnable() //  my scripts custom settings on scene load
    33.     {
    34.         SceneManager.sceneLoaded += InitConfigs;
    35.     }
    36.     private void OnDisable() // my custom
    37.     {
    38.         SceneManager.sceneLoaded -= InitConfigs;
    39.     }
    40.  
    41.     private void InitConfigs(Scene scene, LoadSceneMode mode) // my custom method
    42.     {
    43.         gameManager = FindObjectOfType<GameManager>();
    44.         workShopManager = FindObjectOfType<WorkShopManager>();
    45.         if (gameManager != null && HasAd)
    46.         {
    47.             gameManager.ActivateRewardButton();
    48.         }
    49.     }
    50.  
    51.     void TryInitServices() // my custom method to check for internet, and connect automatically
    52.     {
    53.         // Check if I have internet
    54.         if (Application.internetReachability != NetworkReachability.NotReachable)
    55.         {
    56.             // If I have internet, am I initialized?
    57.             InitServices();
    58.         }
    59.         else // start the process again
    60.         {
    61.             Debug.Log("Internet is NOT REACHABLE for REWARDED AD, trying again in 20 seconds");
    62.             Invoke(nameof(TryInitServices), 20f);
    63.         }
    64.     }
    65.     public async void InitServices()
    66.     {
    67.         try
    68.         {
    69.             InitializationOptions initializationOptions = new InitializationOptions();
    70.             initializationOptions.SetGameId(gameId);
    71.             await UnityServices.InitializeAsync(initializationOptions);
    72.             InitializationComplete();
    73.         }
    74.         catch (Exception e)
    75.         {
    76.             InitializationFailed(e);
    77.         }
    78.     }
    79.  
    80.     public void SetupAd()
    81.     {
    82.         //Create
    83.         ad = MediationService.Instance.CreateRewardedAd(adUnitId);
    84.  
    85.         //Subscribe to events
    86.         ad.OnClosed += AdClosed;
    87.         ad.OnClicked += AdClicked;
    88.         ad.OnLoaded += AdLoaded;
    89.         ad.OnFailedLoad += AdFailedLoad;
    90.         ad.OnUserRewarded += UserRewarded;
    91.  
    92.         // Impression Event
    93.         MediationService.Instance.ImpressionEventPublisher.OnImpression += ImpressionEvent;
    94.     }
    95.     public void Dispose() => ad?.Dispose();
    96.     public async void ShowAd()
    97.     {
    98.         if (ad.AdState == AdState.Loaded)
    99.         {
    100.             try
    101.             {
    102.                 RewardedAdShowOptions showOptions = new RewardedAdShowOptions();
    103.                 showOptions.AutoReload = true;
    104.                 await ad.ShowAsync(showOptions);
    105.                 AdShown();
    106.             }
    107.             catch (ShowFailedException e)
    108.             {
    109.                 AdFailedShow(e);
    110.             }
    111.         }
    112.     }
    113.  
    114.     private void InitializationComplete()
    115.     {
    116.         SetupAd();
    117.         LoadAd();
    118.     }
    119.  
    120.     private async void LoadAd()
    121.     {
    122.         try
    123.         {
    124.             await ad.LoadAsync();
    125.         }
    126.         catch (LoadFailedException)
    127.         {
    128.             // We will handle the failure in the OnFailedLoad callback
    129.         }
    130.     }
    131.  
    132.  
    133.  
    134.     private void InitializationFailed(Exception e)
    135.     {
    136.         Debug.Log("REWAREDED AD Initialization Failed: " + e.Message);
    137.         Debug.Log("REWAREDED AD Initialization Failed: TryInitServices will be called again after 20 secs");
    138.         // now start the loops to check if internet is connected.
    139.         Invoke(nameof(TryInitServices), 20f);
    140.     }
    141.  
    142.     private void AdLoaded(object sender, EventArgs e)
    143.     {
    144.         Debug.Log("REWARDED Ad loaded");
    145.         HasAd = true;
    146.         errorLoadingAdCount = 0;
    147.         if (gameManager != null) gameManager.ActivateRewardButton();
    148.     }
    149.  
    150.     private void AdFailedLoad(object sender, LoadErrorEventArgs e) // Customized method
    151.     {
    152.         Debug.Log("Failed to ANDROID REWARDED ad");
    153.         Debug.Log(e.Message);
    154.         HasAd = false;
    155.         if (gameManager != null) gameManager.DeactivateRewardButton();
    156.         Debug.LogWarning("Failed to LOAD REWARDED ad: ");
    157.         adLoadErrorE = e.Message + "\nLoadError: " +e.Error;
    158.         switch (e.Error)
    159.         {
    160.             // when it is not connected or initialized, let it break out and try again.
    161.             case LoadError.SdkNotInitialized:
    162.             case LoadError.NetworkError:
    163.             case LoadError.MissingMandatoryMemberValues:
    164.             case LoadError.Unknown:
    165.                 Debug.Log("Detected a not connected or unitialized type of error during REWARDED ad load call. Invoking TryInitServices in 20 secs");
    166.                 Invoke(nameof(TryInitServices), 20f);
    167.                 break;
    168.  
    169.             // it is connected.
    170.             case LoadError.TooManyLoadRequests:
    171.                 Debug.Log("Detected Too many ad load requests type error during REWARDED ad load. Canceling all invoke calls, and trying to load ad again after period of 60 seconds");
    172.                 CancelInvoke();
    173.                 Invoke(nameof(LoadAd), 60f);
    174.                 break;
    175.  
    176.             case LoadError.NoFill:
    177.                 Debug.Log("Detected REWARDED No-Fill, trying a REWARDED load call in 20 seconds");
    178.                 Invoke(nameof(LoadAd), 20f);
    179.                 break;
    180.  
    181.             default:
    182.                 Debug.Log("Detected default condition of 2 possible REWARDED AdUnit Showing Or REWARDED ad Unit loading, returning");
    183.                 return;
    184.         }
    185.         errorLoadingAdCount++;
    186.         // for extra precaustion that is probably not needed, if there are 20 faulty ad calls, initiate
    187.         // TryingInitServices(); again.
    188.         if (errorLoadingAdCount >= 20f)
    189.         {
    190.             Debug.Log("Serveral REWARDED Ad Load failed calls for unknown reasons. 20x in row, entering TryInitServices Loop in 20 seconds");
    191.             TryInitServices();
    192.         }
    193.     }
    194.  
    195.     private void AdShown()
    196.     {
    197.         Debug.Log("REWARDED Ad shown!");
    198.     }
    199.  
    200.     private void AdClosed(object sender, EventArgs e)
    201.     {
    202.         Debug.Log("REWARDED Ad has closed");
    203.         // Execute logic after an ad has been closed.
    204.     }
    205.  
    206.     private void AdClicked(object sender, EventArgs e)
    207.     {
    208.         Debug.Log("REWARDED Ad has been clicked");
    209.         // Execute logic after an ad has been clicked.
    210.     }
    211.  
    212.     private void AdFailedShow(ShowFailedException e)
    213.     {
    214.         Debug.Log(e.Message);
    215.     }
    216.  
    217.     private void ImpressionEvent(object sender, ImpressionEventArgs args)
    218.     {
    219.         var impressionData = args.ImpressionData != null ? JsonUtility.ToJson(args.ImpressionData, true) : "null";
    220.         Debug.Log("Impression event from REWARDEDED ad unit id " + args.AdUnitId + " " + impressionData);
    221.     }
    222.  
    223.     private void UserRewarded(object sender, RewardEventArgs e)
    224.     {
    225.         Debug.Log($"Received reward: type:{e.Type}; amount:{e.Amount}");
    226.         workShopManager?.OnAdShown();
    227.         gameManager?.RewardForWatching();
    228.     }
    229. }
    Note*, I'd like to mention that re-initializing may break other parts of the game, such as unity authentication and unity netcode. So this is not the correct solution. As Declas wrote under, once it is initialized, there is no need to initialize again and again, so it is probably best just call loadad calls in this case.
     
    Last edited: Oct 15, 2022
    DeclanMcPartlin likes this.
  2. DeclanMcPartlin

    DeclanMcPartlin

    Unity Technologies

    Joined:
    Nov 19, 2020
    Posts:
    139
    Hi @maxkcy,

    First off, this is great work, great research piece.

    Okay, so I am wondering what the refresh rate for mediation is because often I get no fill item (even when I'm using test ads, that's fine though since I am getting test ads nontheless).
    This is a known issue currently happening with Unity Ads, we will let you know as soon as this is fixed on Unity Ads.

    I want to know 2 things about connection interrupts, and how the ads sdk handles the situation;
    • when ads are initialized at the begining when the user has internet turned off, but later during the session the internet is reconnected
    If there is no internet connection and Initialize is called, the Initialize attempt should fail, no retry will occur on the SDK side (the same goes for load attempts).
    • when internet connection is abruptly lost mid session after initialization, but is reconnected later on
    This depends, I believe. But generally once the internet connection is restored, you should be able to load and show ads again without reinitializing.

    • how to fetch new ads when ads have been shows and no new ad is loaded
    The Load call itself is the only option when attempting to fetch ads, if I understand your question correctly
    • how to check for internet, and send a call to reconnect if connection was disrupted.
    I believe you've answered this yourself in your snippet (check for internet), as for reconnecting, did you experience any issues loading and showing ads after successfully reconnecting back to the internet?
     
unityunity