LoginSignup
2
2

Unity googleAdMobでつまづいた箇所

Posted at

まず言いたい

公式のガイドがおかしい

公式が違うとどうすればいいの?ほんとに!

とくにDestroyAd();
とあるがそんなものガイドにはないよ
ライブラリでもないし。
で、どうしたか
githubからSampleCodeを見てDestroyAd()をどう実装しているかを確認した。

        /// <summary>
        /// Destroys the ad.
        /// When you are finished with a BannerView, make sure to call
        /// the Destroy() method before dropping your reference to it.
        /// </summary>
        public void DestroyAd()
        {
            if (_bannerView != null)
            {
                Debug.Log("Destroying banner view.");
                _bannerView.Destroy();
                _bannerView = null;
            }

            // Inform the UI that the ad is not ready.
            AdLoadedStatus?.SetActive(false);
        }

個人的につまづいた箇所

現状のエラー

再生と停止をしてるのだけど、なぜか関数が2回呼ばれる。
再生時、と停止時に。
Animation.gif
そしてObjectも再生するたびに増えていく
image.png
以下コード

using Assets.MyScripts.BaseUtil;
using System.Collections;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using GoogleMobileAds;
using GoogleMobileAds.Api;
using System;


namespace Assets._00_Project._01_Script._90_BaseUtil._02_Util
{
#if UNITY_EDITOR
    [CustomEditor(typeof(AdsUtil))]
    public class AdsUtilEditor : Editor
    {
        public override void OnInspectorGUI()
        {
            var helpTxt = "ヘルプ情報";
            EditorGUILayout.HelpBox(helpTxt, MessageType.None);

            //元のInspectorを表示
            base.OnInspectorGUI();
            //スペースを追加
            GUILayout.Space(20);

        }
    }
# endif

    /// <summary>
    /// AdsUtil 広告に関する機能を提供するクラス
    /// </summary>
    public class AdsUtil : UnityBaseUtil 
    {
        private Game_PM game_PM;
        [Button("ShowBannerAd")]
        public bool showBannerAd;
        [Button("HideBannerAd")]
        public bool hideBannerAd;

        [SerializeField] private bool enAds;
        [SerializeField]private  bool isTestMode;
        string adUnitId = null; // This will remain null for unsupported platforms.

/// <summary>
        /// UI element activated when an ad is ready to show.
        /// </summary>
        public GameObject AdLoadedStatus;

#if UNITY_IOS                
        [SerializeField] string iOSAdUnitId;
#elif UNITY_ANDROID
        [SerializeField] string androidAdUnitId;
#endif
        [SerializeField] private BannerView _bannerView;

        void Start()
        {

            Init();
            LoadAd();
        }
        public override void Init()
        {

            game_PM = Resources.Load<Game_PM>("Game_PM");


#if UNITY_EDITOR
            adUnitId = "ca-app-pub-3940256099942544/6300978111";//テスト用UnitID
#elif UNITY_ANDROID
            adUnitId = androidAdUnitId;
#elif UNITY_IOS
            adUnitId = iOSAdUnitId;
#else

#endif
            if(enAds){
                // Initialize the Google Mobile Ads SDK.
                MobileAds.Initialize(initStatus => { });

            }

    
        }
        public override void CycleSt()
        {

        }
        public override void CycleDisp()
        {

        }


        private void OnGUI()
        {
#if DEBUG
            if (game_PM.EnDebagModeDisp == EN_DEBAG_MODE.None)
            {
            }
#endif
}
        /// <summary>
        /// Creates a 320x50 banner at top of the screen.
        /// </summary>
        public void CreateBannerView()
        {
            Debug.Log("Creating banner view.");

            // If we already have a banner, destroy the old one.
            if (_bannerView != null)
            {
                DestroyAd();
            }

            // Create a 320x50 banner at top of the screen.
            _bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);

            // Listen to events the banner may raise.
            ListenToAdEvents();

            Debug.Log("Banner view created.");
        }
        /// <summary>
        /// Creates the banner view and loads a banner ad.
        /// </summary>
        public void LoadAd()
        {
            // Create an instance of a banner view first.
                if (_bannerView == null)
                {
                    CreateBannerView();
                }

                // Create our request used to load the ad.
                var adRequest = new AdRequest();

                // Send the request to load the ad.
                Debug.Log("Loading banner ad.");
                _bannerView.LoadAd(adRequest);
}
        /// <summary>
        /// Shows the ad.
        /// </summary>
        public void ShowAd()
        {
            if (_bannerView != null)
            {
                Debug.Log("Showing banner view.");
                _bannerView.Show();
            }
        }
        /// <summary>
        /// Hides the ad.
        /// </summary>
        public void HideAd()
        {
            if (_bannerView != null)
            {
                Debug.Log("Hiding banner view.");
                _bannerView.Hide();
            }
        }
        /// <summary>
        /// Destroys the ad.
        /// When you are finished with a BannerView, make sure to call
        /// the Destroy() method before dropping your reference to it.
        /// </summary>
        public void DestroyAd()
                    {
                if (_bannerView != null)
                {
Debug.Log("Destroying banner view.");
                    _bannerView.Destroy();
                    _bannerView = null;
                    }

            // Inform the UI that the ad is not ready.
            AdLoadedStatus?.SetActive(false);
        }
        /// <summary>
        /// Listen to events the banner may raise.
        /// </summary>
        private void ListenToAdEvents()
        {
            // Raised when an ad is loaded into the banner view.
            _bannerView.OnBannerAdLoaded += () =>
            {
                Debug.Log("Banner view loaded an ad with response : "
                    + _bannerView.GetResponseInfo());

                // Inform the UI that the ad is ready.
                AdLoadedStatus?.SetActive(true);
            };
            // Raised when an ad fails to load into the banner view.
            _bannerView.OnBannerAdLoadFailed += (LoadAdError error) =>
            {
                Debug.LogError("Banner view failed to load an ad with error : " + error);
            };
            // Raised when the ad is estimated to have earned money.
            _bannerView.OnAdPaid += (AdValue adValue) =>
            {
                Debug.Log(String.Format("Banner view paid {0} {1}.",
                    adValue.Value,
                    adValue.CurrencyCode));
            };
            // Raised when an impression is recorded for an ad.
            _bannerView.OnAdImpressionRecorded += () =>
            {
                Debug.Log("Banner view recorded an impression.");
            };
            // Raised when a click is recorded for an ad.
            _bannerView.OnAdClicked += () =>
            {
                Debug.Log("Banner view was clicked.");
            };
            // Raised when an ad opened full screen content.
            _bannerView.OnAdFullScreenContentOpened += () =>
            {
                Debug.Log("Banner view full screen content opened.");
            };
            // Raised when the ad closed full screen content.
            _bannerView.OnAdFullScreenContentClosed += () =>
            {
                Debug.Log("Banner view full screen content closed.");
            };
        }

        public void HideBannerAd()
        {
            HideAd();
        }
        public void ShowBannerAd()
        {
            ShowAd();
        }
        
/*        private void OnDestroy()
        {
            DestroyBannerView();
        }
        private void OnApplicationQuit()
        {
            DestroyBannerView();
        }*/
    }
}

修正した箇所

原因は不明だが同じようなエラーの人のために記載しておく。
ます私はMonoBehaviourを継承したカスタムクラスを使用している。それをMonoBhaviourを直接継承にした。
それと
public class AdsUtilEditor : Editor

Editorのカスタムも削除した。
影響がないと思っていたがこれをやめたらうまく動くようになった。
どうしても原因がわからないときは試してみるとよいかも。

修正後のソース

using Assets.MyScripts.BaseUtil;
using System.Collections;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using GoogleMobileAds;
using GoogleMobileAds.Api;
using System;


namespace Assets._00_Project._01_Script._90_BaseUtil._02_Util
{

    /// <summary>
    /// AdsUtil 広告に関する機能を提供するクラス
    /// </summary>
    public class AdsUtil : MonoBehaviour 
    {
        private Game_PM game_PM;

        [SerializeField] private bool enAds;
        [SerializeField]private  bool isTestMode;
        string adUnitId = null; // This will remain null for unsupported platforms.

/// <summary>
        /// UI element activated when an ad is ready to show.
        /// </summary>
        public GameObject AdLoadedStatus;

#if UNITY_IOS                
        [SerializeField] string iOSAdUnitId;
#elif UNITY_ANDROID
        [SerializeField] string androidAdUnitId;
#endif
        [SerializeField] private BannerView _bannerView;

        void Start()
        {

            Init();
            LoadAd();
        }
        public void Init()
        {

            game_PM = Resources.Load<Game_PM>("Game_PM");


#if UNITY_EDITOR
            adUnitId = "ca-app-pub-3940256099942544/6300978111";//テスト用UnitID
#elif UNITY_ANDROID
            adUnitId = androidAdUnitId;
#elif UNITY_IOS
            adUnitId = iOSAdUnitId;
#else

#endif
            if(enAds){
                // Initialize the Google Mobile Ads SDK.
                MobileAds.Initialize(initStatus => { });

            }

    
        }


        /// <summary>
        /// Creates a 320x50 banner at top of the screen.
        /// </summary>
        public void CreateBannerView()
        {
            Debug.Log("Creating banner view.");
            
            // If we already have a banner, destroy the old one.
            if (_bannerView != null)
            {
                DestroyAd();
            }

            // Create a 320x50 banner at top of the screen.
            _bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
            Debug.Log("Banner view created.");
        }
        /// <summary>
        /// Creates the banner view and loads a banner ad.
        /// </summary>
        public void LoadAd()
        {
            // Create an instance of a banner view first.
                if (_bannerView == null)
                {
                    CreateBannerView();
                }

                // Create our request used to load the ad.
                var adRequest = new AdRequest();

                // Send the request to load the ad.
                Debug.Log("Loading banner ad.");
                _bannerView.LoadAd(adRequest);
}
        /// <summary>
        /// Shows the ad.
        /// </summary>
        public void ShowAd()
        {
            if (_bannerView != null)
            {
                Debug.Log("Showing banner view.");
                _bannerView.Show();
            }
        }
        /// <summary>
        /// Hides the ad.
        /// </summary>
        public void HideAd()
        {
            if (_bannerView != null)
            {
                Debug.Log("Hiding banner view.");
                _bannerView.Hide();
            }
        }
        /// <summary>
        /// Destroys the ad.
        /// When you are finished with a BannerView, make sure to call
        /// the Destroy() method before dropping your reference to it.
        /// </summary>
        public void DestroyAd()
                    {
                if (_bannerView != null)
                {
                    Debug.Log("Destroying banner view.");
                    _bannerView.Destroy();
                    _bannerView = null;
                }

            // Inform the UI that the ad is not ready.
            //AdLoadedStatus?.SetActive(false);
        }
        /// <summary>
        /// Listen to events the banner may raise.
        /// </summary>
        private void ListenToAdEvents()
        {
            // Raised when an ad is loaded into the banner view.
            _bannerView.OnBannerAdLoaded += () =>
            {
                Debug.Log("Banner view loaded an ad with response : "
                    + _bannerView.GetResponseInfo());

                // Inform the UI that the ad is ready.
                AdLoadedStatus?.SetActive(true);
            };
            // Raised when an ad fails to load into the banner view.
            _bannerView.OnBannerAdLoadFailed += (LoadAdError error) =>
            {
                Debug.LogError("Banner view failed to load an ad with error : " + error);
            };
            // Raised when the ad is estimated to have earned money.
            _bannerView.OnAdPaid += (AdValue adValue) =>
            {
                Debug.Log(String.Format("Banner view paid {0} {1}.",
                    adValue.Value,
                    adValue.CurrencyCode));
            };
            // Raised when an impression is recorded for an ad.
            _bannerView.OnAdImpressionRecorded += () =>
            {
                Debug.Log("Banner view recorded an impression.");
            };
            // Raised when a click is recorded for an ad.
            _bannerView.OnAdClicked += () =>
            {
                Debug.Log("Banner view was clicked.");
            };
            // Raised when an ad opened full screen content.
            _bannerView.OnAdFullScreenContentOpened += () =>
            {
                Debug.Log("Banner view full screen content opened.");
            };
            // Raised when the ad closed full screen content.
            _bannerView.OnAdFullScreenContentClosed += () =>
            {
                Debug.Log("Banner view full screen content closed.");
            };
        }

        public void HideBannerAd()
        {
            HideAd();
        }
        public void ShowBannerAd()
        {
            ShowAd();
        }
        
        private void OnDestroy()
        {
            DestroyAd();
        }
/*         private void OnApplicationQuit()
        {
            DestroyBannerView();
        } */
    }
}

終わりに

公式リファレンスはちゃんとしてね。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2