- Home /
Google Ads BannerView persists across scenes
I have this issue where the ad banner gets destroyed when you leave the menu scene, but if you leave the scene before the ad is actually fetched, it will show up in the game scene. Now there is no reference to it, and there is no code to destroy it. There is also no way to even check the status of an ad as far as I can tell, so the only solution I have been able to come up with is keeping a static reference to the banner, and calling destroy on it every update cycle in the game scene. This seems bad, but I can't really think of a better way of doing it. Any ideas?
Answer by Neamtzu · Mar 06, 2015 at 04:35 PM
If you're using the AdMob plugin from Prime31 you should do something like this
public class AdsController : MonoBehaviour {
public static AdsController Instance;
void Awake() {
if (Instance == null) {
Instance = this;
DontDestroyOnLoad (this.gameObject);
}
else
Destroy (this.gameObject);
}
void OnEnable() {
AdMobAndroidManager.receivedAdEvent += receivedAdEvent;
}
void OnDisable() {
AdMobAndroidManager.receivedAdEvent -= receivedAdEvent;
}
public void showAd() {
AdMobAndroid.createBanner( "test", AdMobAndroidAd.smartBanner, AdMobAdPlacement.BottomCenter );
}
public void destroyAd() {
AdMobAndroid.destroyBanner();
}
void receivedAdEvent() {
if (Application.loadedLevelName == "Game_Scene")
destroyAd ();
}
}
You should add this script on a gameobject on your first scene. At runtime only 1 instance of the this class will be available in every scene of your project. In your case, the add will be called in your menu scene, if the game scene will be loaded before the ad was showed, in the game scene this script will catch the received ad event, will check if it is game scene and if so it will destroy the banner.
Use this if you want to diplay an ad
AdsController.Instance.showAd();
If you're using another plugin, you should change "AdMobAndroidManager.receivedAdEvent" with the correspondent received ad event from your plugin.
I hope this helps.
I am using the official plugin: https://github.com/googleads/googleads-mobile-plugins/releases/tag/v2.1
I see based on your code that I should be using the event callbacks to destroy the ad rather than try to manually check if it is loaded, and this plugin has similar functions so I should be able to implement the callbacks in the same way.
If you look here you can see the callbacks they provide: https://github.com/googleads/googleads-mobile-plugins/blob/master/unity/source/Assets/Google$$anonymous$$obileAds/Api/BannerView.cs#L10
Yes, check when the "AdOpened" is triggered if you're in game scene. If so, destroy the banner.