2016-08-11 65 views
0

我在Unity中提供InterstitialAds的代码,并且我希望每次启动此全屏广告时,当关闭和新级别启动时,所以我使用OnDestroy函数,但是当我必须调用interstitial.destroy();?之间:代码是否适合游戏的流畅运行?感谢所有的答案,对不起我的英文:)Unity中的InterstitialAds

public class GoogleAdsScript : MonoBehaviour 
    { 
     bool isLoaded = false; 
     private InterstitialAd interstitial; 
     private BannerView bannerView; 

     void Start() 
     { 
      RequestInterstitial(); 

      //RequestBanner(); 
     } 

     void OnDestroy() 
     { 
      if (interstitial.IsLoaded() && isLoaded == false) 
      { 
       interstitial.Show(); 
       isLoaded = true; 
      } 
     } 

     private void RequestInterstitial() 
     { 
    #if UNITY_ANDROID 
      string adUnitId = "ca-app-pub-3940256099942544/1033173712"; 
    #elif UNITY_IPHONE 
      string adUnitId = "INSERT_IOS_INTERSTITIAL_AD_UNIT_ID_HERE"; 
    #else 
      string adUnitId = "unexpected_platform"; 
    #endif 

      // Initialize an InterstitialAd. 
      interstitial = new InterstitialAd(adUnitId); 
      // Create an empty ad request. 
      AdRequest request = new AdRequest.Builder().Build(); 
      // Load the interstitial with the request. 
      interstitial.LoadAd(request); 
     } 

     private void RequestBanner() 
     { 
    #if UNITY_ANDROID 
      string adUnitId = "ca-app-pub-3940256099942544/6300978111"; 
    #elif UNITY_IPHONE 
      string adUnitId = "INSERT_IOS_BANNER_AD_UNIT_ID_HERE"; 
    #else 
      string adUnitId = "unexpected_platform"; 
    #endif 

      // Create a 320x50 banner at the top of the screen. 
      bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Top); 
      // Create an empty ad request. 
      AdRequest request = new AdRequest.Builder().Build(); 
      // Load the banner with the request. 
      bannerView.LoadAd(request); 
     } 


    } 

回答

1

如果持有该InterstitialAd实例引用(interstitial)脚本(GoogleAdsScript)即将毁灭,你应该叫interstitial.destroy();。你这样做,这样你就不会失去参考。

我的建议是使GoogleAdsScript脚本中的重要功能为public。将GoogleAdsScript附加到GameObject,名称为AdsObj。 把DontDestroyOnLoad(transform.gameObject);放在Awake()函数的GoogleAdsScript脚本中,这样它在加载新场景时不会破坏。您现在可以从其他脚本访问GoogleAdsScript以显示或隐藏广告。

public class OtherScript : MonoBehaviour 
{ 
    public GoogleAdsScript googleAds; 

    void Start() 
    { 
     googleAds = GameObject.Find("AdsObj").GetComponent<GoogleAdsScript>(); 
     googleAds.RequestInterstitial();//Assumes that RequestInterstitial is now public 
    } 
} 

没有理由再破坏GoogleAdsScript脚本。

+0

必须调用interstitial.destroy(),如果我在每个第三级使用广告? – Adam

+0

你听起来像你不明白我的答案。你可以问问题,如果它的任何部分是令人困惑的。如果你做'interstitial = new InterstitialAd(adUnitId);',你必须在'OnDestroy'或'OnDisable'函数中执行'interstitial.destroy();'。我向您展示了一种在场景中只有一个包含所有内容的“GoogleAdsScript”的方法。如果您在我的回答中遵循该方向,则不会必须销毁它 – Programmer

+0

我更改了脚本:void更新() if(interstitial.IsLoaded()&& isLoaded == false) {interstitial.Show() ; isLoaded = true; } } void OnDestroy() if(interstitial.IsLoaded())interstitial.Destroy(); }'这是干净的方式吗? – Adam