2016-08-11 68 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