Search code examples
iosamazon-advertising-api

How to hide amazon ads in unity


So I integrated amazon mobile ads into my unity/ios project. I have it all working to where I hide the ads every time a scene changes. Every time I open a scene, the ad shows. So it's all working fine except when you change scenes really quickly. I don't want ads in the main game as it obstructs the view of the users. Every time you get to the retry scene, if you quickly switch from that scene right before an ad loads, that ad will get stuck on the next scene which makes another ad show on top of it. Every time a scene changes it should be hiding the ad not matter how fast you change scenes. Is there any way to make sure it hides the ad if an ad is shown? I'm using the code below:

void Start() {
    mobileAds = AmazonMobileAdsImpl.Instance;
    ApplicationKey key = new ApplicationKey();
    key.StringValue = iosKey;
    mobileAds.SetApplicationKey(key);

    ShouldEnable enable = new ShouldEnable();
    enable.BooleanValue = true;
    mobileAds.EnableTesting(enable);
    mobileAds.EnableLogging(enable);

    Placement placement = new Placement();
    placement.Dock = Dock.BOTTOM;
    placement.HorizontalAlign = HorizontalAlign.CENTER;
    placement.AdFit = AdFit.FIT_AD_SIZE;
    response = mobileAds.CreateFloatingBannerAd(placement);
    string adType = response.AdType.ToString();
    long identifer = response.Identifier;

    newResponse = mobileAds.LoadAndShowFloatingBannerAd(response);
    bool loadingStarted = newResponse.BooleanValue;
}


void OnDestroy() {
    mobileAds.CloseFloatingBannerAd(response);
    response = null;
    mobileAds = null;
    newResponse = null;
}

Solution

  • The close ad API

     mobileAds.CloseFloatingBannerAd(response);  
    

    will only work if the ad is already loaded. You need to register for the ad loaded event. If the scene is destroyed, then you would close the ad when the ad loaded event tiggers.

    You can register for AdLoaded event as follows, Documentation

        using com.amazon.mas.cpt.ads;
    
        bool sceneDestroyed = false;  //tracks if scene is destroyed
    
    
    
        //Obtain object used to interact with the plugin
        IAmazonMobileAds mobileAds = AmazonMobileAdsImpl.Instance;
    
    
        // Define event handler
        private void EventHandler(Ad args)
        {
           if (sceneDestroyed)
           {
                mobileAds.CloseFloatingBannerAd(response);
           }
           else
           {
               //Do some other job
           }
        }
    
        //Register for an event
        mobileAds.AddAdLoadedListener(EventHandler);
    
        void OnDestroy() 
        {
                    sceneDestroyed = true;
        }