I just finished adding admob to my game and now the game is very jerky. The profiler is showing that GC is very busy. Am I doing something wrong with my code? Am I not destroying the ad properly after use? Also, don't know if its connected, have I misused "this" too many times? Ay help would be appreciated. Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
using System;
public class AdMob : MonoBehaviour
{
public int deathCountForAd;
private InterstitialAd interstitial;
private static AdMob instance = null;
public static AdMob Instance
{
get { return instance; }
}
void Awake()
{
if (instance != null && instance != this)
{
Destroy(this.gameObject);
return;
}
else
{
instance = this;
}
DontDestroyOnLoad(this.gameObject);
}
public void Start()
{
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(initStatus => { });
RequestInterstitial();
}
private void RequestInterstitial()
{
#if UNITY_ANDROID
string adUnitId = "**************************";
#elif UNITY_IPHONE
string adUnitId = "**************************";
#else
string adUnitId = "unexpected_platform";
#endif
// Clean up interstitial ad before creating a new one.
if (this.interstitial != null)
{
this.interstitial.Destroy();
}
// Create an interstitial.
this.interstitial = new InterstitialAd(adUnitId);
// Called when an ad request has successfully loaded.
this.interstitial.OnAdLoaded += HandleOnAdLoaded;
// Called when an ad request failed to load.
this.interstitial.OnAdFailedToLoad += HandleOnAdFailedToLoad;
// Called when an ad is shown.
this.interstitial.OnAdOpening += HandleOnAdOpening;
// Called when the ad is closed.
this.interstitial.OnAdClosed += HandleOnAdClosed;
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
this.interstitial.LoadAd(request);
}
public void HandleOnAdLoaded(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLoaded event received");
}
public void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
MonoBehaviour.print("HandleFailedToReceiveAd event received with message: "
+ args);
}
public void HandleOnAdOpening(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdOpening event received");
}
public void HandleOnAdClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdClosed event received");
RequestInterstitial();
}
public void ShowAd()
{
if (this.interstitial.IsLoaded())
{
this.interstitial.Show();
}
}
}
↧