Search Unity

ADBannerView problem when reloading scene (with solution!)

Discussion in 'iOS and tvOS' started by kerede, Feb 22, 2014.

  1. kerede

    kerede

    Joined:
    Apr 3, 2013
    Posts:
    9
    This one caused me a few days of headache… I have a single-scene game with an ADBannerView at the top. When the player dies, I simply reload the scene to restart (not sure if this is the right approach, but it's easy!)

    I was seeing all sorts of strange behavior with the iAd. Sometimes it was white, sometimes it flickered in and out. It took me a long time to realize that each time I reloaded my scene another ADBannerView was being added to the screen! As you can imagine, this causes a host of issues, but the most noticeable one is a white (empty) banner when the topmost banner is hidden due to an error.

    I needed a quick fix, so I made sure only one iAd would be created and reused across scene reloads. Here's how I did it:

    Added an empty object with the following script attached:

    Code (csharp):
    1.  
    2. public class PersistentAds : MonoBehaviour
    3. {
    4.     void Update()
    5.     {
    6.         if (!GameObject.Find("Ads"))
    7.         {
    8.             GameObject ads = new GameObject();
    9.             ads.name = "Ads";
    10.             ads.AddComponent<Ads>();
    11.         }
    12.  
    13.         this.enabled = false;
    14.     }
    15. }
    16.  
    And here's the Ads script, which isn't destroyed on load:

    Code (csharp):
    1.  
    2. public class Ads : MonoBehaviour
    3. {
    4.     private ADBannerView banner = null;
    5.    
    6.     void Start()
    7.     {
    8.         GameObject.DontDestroyOnLoad(gameObject);
    9.  
    10.         if (banner == null)
    11.         {
    12.             banner = new ADBannerView(ADBannerView.Type.Banner, ADBannerView.Layout.Top);
    13.             ADBannerView.onBannerWasClicked += OnBannerClicked;
    14.             ADBannerView.onBannerWasLoaded  += OnBannerLoaded;
    15.         }
    16.     }
    17.    
    18.     void OnBannerLoaded()
    19.     {
    20.         if (banner != null)
    21.         {
    22.             banner.visible = true;
    23.         }
    24.     }
    25. }
    26.  
    This fixed the issue for me. I do think the ADBannerView documentation needs some clarification if this is behaving as intended. Or better yet, it should prevent multiple ad views from being created under the hood.

    Hope this saves someone else some time!