LoginSignup
0
0

【Unity】Admobのバナーをボタンクリック等の操作で消す方法(表示非表示を切り替える)

Posted at

はじめに

本記事では、UnityでAdmobバナーを使用している人の中で、ある操作でバナーを非表示にしたいけどやり方が分からない人に向けた記事です。

実装したコード

using UnityEngine;
using GoogleMobileAds.Api;

public class AdmobManager : MonoBehaviour
{

    public void Start()
    {
        // Initialize the Google Mobile Ads SDK.
        MobileAds.Initialize((InitializationStatus initStatus) => { });
        LoadAd();
    }

    // These ad units are configured to always serve test ads.
#if UNITY_ANDROID
  private string _adUnitId = "ca-app-pub-3940256099942544/6300978111";
#elif UNITY_IPHONE
  private string _adUnitId = "ca-app-pub-3940256099942544/2934735716";
#else
    private string _adUnitId = "unused";
#endif

    BannerView _bannerView = null;

    /// Creates a 320x50 banner view at top of the screen.
    public void CreateBannerView()
    {
        Debug.Log("Creating banner view");

        if (_bannerView != null)
        {
            _bannerView.Destroy();
            _bannerView = null;
        }

        _bannerView = new BannerView(_adUnitId, AdSize.Banner, AdPosition.Top);
    }

    /// Creates the banner view and loads a banner ad.
    public void LoadAd()
    {
        CreateBannerView();

        var adRequest = new AdRequest();

        Debug.Log("Loading banner ad.");
        _bannerView.LoadAd(adRequest);
    }

    /// Destroys the banner view.
    public void DestroyBannerView()
    {
        if (_bannerView != null)
        {
            Debug.Log("Destroying banner view.");
            _bannerView.Destroy();
            _bannerView = null;
        }
    }
}

ボタンクリックでバナーを非表示にする

ボタンのクリック動作に対して、DestroyBannerView関数を割り当てることで実装可能です。

Movie_002.gif

非表示にしたバナーを再度表示する

ボタンのクリック動作にLoadAd関数を割り当てることで実装できます。

Movie_003.gif

0
0
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
0
0