facebook twitter hatena line email

「Unity/GoogleMobileAds/Banner」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(広告が出なくなった時の対応方法)
(広告の高さのサイズを取得)
 
(同じ利用者による、間の31版が非表示)
行48: 行48:
 
         // Create a 320x50 banner at the top of the screen.
 
         // Create a 320x50 banner at the top of the screen.
 
         bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
 
         bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
 +
        // Called when an ad request has successfully loaded.
 +
        bannerView.OnAdLoaded += HandleOnAdLoaded;
 +
        // Called when an ad request failed to load.
 +
        bannerView.OnAdFailedToLoad += HandleOnAdFailedToLoad;
 +
        // Called when an ad is clicked.
 +
        bannerView.OnAdOpening += HandleOnAdOpened;
 +
        // Called when the user returned from the app after an ad click.
 +
        bannerView.OnAdClosed += HandleOnAdClosed;
 +
        // Called when the ad click caused the user to leave the application.
 +
        bannerView.OnAdLeavingApplication += HandleOnAdLeavingApplication;
 +
        AdRequest request = new AdRequest.Builder().Build();
 +
        bannerView.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.Message);
 +
    }
 +
 +
    public void HandleOnAdOpened(object sender, EventArgs args)
 +
    {
 +
        MonoBehaviour.print("HandleAdOpened event received");
 +
    }
 +
 +
    public void HandleOnAdClosed(object sender, EventArgs args)
 +
    {
 +
        MonoBehaviour.print("HandleAdClosed event received");
 +
    }
 +
 +
    public void HandleOnAdLeavingApplication(object sender, EventArgs args)
 +
    {
 +
        MonoBehaviour.print("HandleAdLeavingApplication event received");
 
     }
 
     }
 
}
 
}
行53: 行90:
 
参考:
 
参考:
 
https://developers.google.com/admob/unity/banner
 
https://developers.google.com/admob/unity/banner
 
==firebaseと共存の場合の場合==
 
java.lang.RuntimeException: Unable to get provider com.google.android.gms.ads.MobileAdsInitProvider: java.lang.IllegalStateException: Invalid application IDが発生する
 
 
Assets/Plugins/Android/GoogleMobileAdsPlugin/AndroidManifest.xmlの[ADMOB APPLICATION ID]にadmobのAppIDを入れれば良い
 
<pre>
 
<?xml version="1.0" encoding="utf-8"?>
 
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 
    package="com.google.unity.ads"
 
    android:versionName="1.0"
 
    android:versionCode="1">
 
  <uses-sdk android:minSdkVersion="14"
 
      android:targetSdkVersion="19" />
 
  <application>
 
    <uses-library android:required="false" android:name="org.apache.http.legacy"/>
 
    <meta-data
 
    android:name="com.google.android.gms.ads.APPLICATION_ID"
 
    android:value="[ADMOB APPLICATION ID]"/>
 
  </application>
 
</manifest>
 
</pre>
 
参考:https://developers.google.com/admob/android/quick-start#update_your_androidmanifestxml
 
  
 
==広告削除==
 
==広告削除==
行82: 行97:
 
==サイズ==
 
==サイズ==
 
  AdSize.Banner 320×50 標準のバナー
 
  AdSize.Banner 320×50 標準のバナー
AdSize.LargeBanner 320×100 バナー(大)
 
 
  AdSize.MediumRectangle 300×250 IAB レクタングル(中)
 
  AdSize.MediumRectangle 300×250 IAB レクタングル(中)
  AdSize.FullBanner 468×60 IAB フルサイズ バナー
+
  AdSize.IABBanner 468×60 IAB フルサイズ バナー
 
  AdSize.Leaderboard 728×90 IAB ビッグバナー
 
  AdSize.Leaderboard 728×90 IAB ビッグバナー
 
  AdSize.SmartBanner  画面の幅×32|50|90
 
  AdSize.SmartBanner  画面の幅×32|50|90
行167: 行181:
 
     string GetAdUnitId() {
 
     string GetAdUnitId() {
 
         #if UNITY_ANDROID
 
         #if UNITY_ANDROID
             string adUnitId = "ca-app-pub-3940256099942544/6300978111";
+
             string adUnitId = "ca-app-pub-3940256099942544/6300xxxxxx";
 
         #elif UNITY_IPHONE
 
         #elif UNITY_IPHONE
             string adUnitId = "ca-app-pub-3940256099942544/2934735716";
+
             string adUnitId = "ca-app-pub-3940256099942544/2934xxxxxx";
 
         #else
 
         #else
 
             string adUnitId = "unexpected_platform";
 
             string adUnitId = "unexpected_platform";
行292: 行306:
 
#Assets/PlayserviceResolver/AndroidResolver/ForceResolver
 
#Assets/PlayserviceResolver/AndroidResolver/ForceResolver
  
==テスト用==
+
==D8: Program type already present: com.google.unity.ads.Banner$12エラーが出たら==
I/Ads: Use AdRequest.Builder.addTestDevice("33BE2250B43518CCDA7DE426D04EE232")
+
GoogleMobileAdsのversionを更新したなどででるようであれば、一旦Plugins/AndroidやPlugins/iOSを削除
to get test ads on this device.
+
  
AdRequest request = new AdRequest.Builder()
+
*mainTemplate.gradleのフォーマットが変わってた。
  .AddTestDevice("2077ef9a63d2b398840261c8221a0c9b")
+
  .Build();
+
  
https://developers.google.com/admob/unity/test-ads?hl=ja
+
==アダプティブバナー==
 +
320x50の横幅いっぱいのようなレイアウト
 +
 
 +
サンプル
 +
<pre>
 +
AdSize adaptiveSize = AdSize.GetCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(AdSize.FullWidth);
 +
bannerView = new BannerView(adUnitId, adaptiveSize, AdPosition.Bottom);
 +
</pre>
 +
 
 +
* AdSize.GetLandscapeAnchoredAdaptiveBannerAdSizeWithWidth(横向き)
 +
* AdSize.GetPortraitAnchoredAdaptiveBannerAdSizeWithWidth(縦向き)
 +
* AdSize.GetCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(実行時の向き)
 +
 
 +
参考:https://developers.google.com/admob/unity/banner/adaptive?hl=ja
 +
 
 +
===広告の高さのサイズを取得===
 +
注意:テスト環境でのみ有効で、本番環境では"ADAPTIVE(Clone)"のGameObjectが取得できないので、使えなかった。
 +
<pre>
 +
bannerView.OnBannerAdLoaded += () =>
 +
{
 +
GameObject adaptive = GameObject.Find("ADAPTIVE(Clone)");
 +
float scale = adaptive.transform.localScale.y;
 +
float adaptiveAdHeight = scale * bannerView.GetHeightInPixels();
 +
        Debug.Log($"ad loaded height: {adaptiveAdHeight}");
 +
};
 +
</pre>
 +
出力
 +
<pre>
 +
bannerView.GetHeightInPixels()=100
 +
height=169.1667
 +
</pre>
 +
 
 +
参考:https://stackoverflow.com/questions/77169439/get-admob-adaptive-banner-height-on-unity
 +
====広告の高さのサイズをfitさせる例====
 +
<pre>
 +
[SerializeField] RectTransform contentImage;
 +
private AdMobBanner admobBanner;
 +
private void RequestAdmobBanner()
 +
{
 +
admobBanner = new AdMobBanner();
 +
admobBanner.Init();
 +
System.Action<float> callback = (float adaptiveAdHeight) =>
 +
{
 +
AdjustContentBottom(adaptiveAdHeight);
 +
};
 +
admobBanner.RequestAdaptiveBanner(callback);
 +
}
 +
// imageのstretchのbottom更新
 +
private void AdjustContentBottom(float bottom)
 +
{
 +
if (contentImage != null)
 +
{
 +
Vector2 offset = contentImage.offsetMin;
 +
offset.y = bottom;
 +
contentImage.offsetMin = offset;
 +
}
 +
}
 +
</pre>
 +
 
 +
AdMobBanner.cs
 +
<pre>
 +
public void RequestAdaptiveBanner(System.Action<float> callback = null)
 +
{
 +
AdSize adaptiveSize = AdSize.GetCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(AdSize.FullWidth);
 +
bannerView = new BannerView(GetAdUnitId(), adaptiveSize, AdPosition.Bottom);
 +
bannerView.OnBannerAdLoaded += () =>
 +
{
 +
GameObject adaptive = GameObject.Find("ADAPTIVE(Clone)");
 +
float scale = adaptive.transform.localScale.y;
 +
adaptiveAdHeight = scale * bannerView.GetHeightInPixels();
 +
// Debug.Log($"ad loaded height: {adaptiveAdHeight}");
 +
callback(adaptiveAdHeight);
 +
};
 +
bannerView.LoadAd(request);
 +
}
 +
</pre>
 +
 
 +
====広告の高さのサイズをfitさせる例(LayoutElementの場合)====
 +
<pre>
 +
LayoutElement layoutElement = footAdObj.GetComponent<LayoutElement>();
 +
if (layoutElement != null)
 +
{
 +
float space = 10f;
 +
CanvasScaler canvasScaler = canvas.GetComponent<CanvasScaler>();
 +
float scaleFactor = Mathf.Min(
 +
Screen.width / canvasScaler.referenceResolution.x,
 +
Screen.height / canvasScaler.referenceResolution.y
 +
);
 +
        layoutElement.minHeight = adaptiveAdHeight / scaleFactor + space;
 +
// Debug.Log("scaleFactor layoutElement.minHeight=" + layoutElement.minHeight);
 +
}
 +
</pre>
 +
canvasScalerを使ってない場合は、scaleFactorじゃなくて、canvas.transform.localScale.yを使う。

2024年12月19日 (木) 04:31時点における最新版

admob申し込み

https://support.google.com/admob/answer/7356219?hl=ja

アプリID ca-app-pub-0000000000000000~0000000000

広告ID ca-app-pub-0000000000000000/0000000000

などを手に入れる

UnityのAdMobのpluginsのインストール

https://github.com/googleads/googleads-mobile-unity/releases

Assets/ImportPackageからunitypluginを追加

サンプル

using GoogleMobileAds.Api;
public class GoogleMobileAdsDemoScript : MonoBehaviour
{
    private BannerView bannerView;
    public void Start()
    {
        #if UNITY_ANDROID
            string appId = "ca-app-pub-3940256099942544~3347511713";
        #elif UNITY_IPHONE
            string appId = "ca-app-pub-3940256099942544~1458002511";
        #else
            string appId = "unexpected_platform";
        #endif

        // Initialize the Google Mobile Ads SDK.
        MobileAds.Initialize(appId);
        this.RequestBanner();
    }

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

        // Create a 320x50 banner at the top of the screen.
        bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
        // Called when an ad request has successfully loaded.
        bannerView.OnAdLoaded += HandleOnAdLoaded;
        // Called when an ad request failed to load.
        bannerView.OnAdFailedToLoad += HandleOnAdFailedToLoad;
        // Called when an ad is clicked.
        bannerView.OnAdOpening += HandleOnAdOpened;
        // Called when the user returned from the app after an ad click.
        bannerView.OnAdClosed += HandleOnAdClosed;
        // Called when the ad click caused the user to leave the application.
        bannerView.OnAdLeavingApplication += HandleOnAdLeavingApplication;
        AdRequest request = new AdRequest.Builder().Build();
        bannerView.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.Message);
    }

    public void HandleOnAdOpened(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdOpened event received");
    }

    public void HandleOnAdClosed(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdClosed event received");
    }

    public void HandleOnAdLeavingApplication(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdLeavingApplication event received");
    }
}

参考: https://developers.google.com/admob/unity/banner

広告削除

bannerView.Hide();
bannerView.Destroy();

サイズ

AdSize.Banner 320×50	標準のバナー
AdSize.MediumRectangle 300×250	IAB レクタングル(中)
AdSize.IABBanner 468×60	IAB フルサイズ バナー
AdSize.Leaderboard 728×90	IAB ビッグバナー
AdSize.SmartBanner  画面の幅×32|50|90

位置

AdPosition.Top
AdPosition.Bottom
AdPosition.TopLeft
AdPosition.TopRight
AdPosition.BottomLeft
AdPosition.BottomRight
AdPosition.Center

iOSでError running CocoaPods. Please ensure you have at least version 1.0.0. You can install CocoaPods with the Ruby gem package manager:となる場合

sudo gem install -n /usr/local/bin cocoapods
pod setup

上をiosプロジェクト内でコマンド実行

iOSビルドで'GoogleMobileAds/GoogleMobileAds.h' file not foundエラーとなる場合

GoogleMobileAds.frameworkをPlugins/iOSに追加するか上のcocoapodをios_project内で実行する

Androidビルドでunable to merge android manifest see the console for more details エラー

2つAndroidManifest.xmlがありsdkバージョンなどが違うとこのエラーが出る。

Assets/Plugins/Android/AndroidManifest.xml
Assets/Plugins/Android/GoogleMobileAdsPlugin/AndroidManifest.xml

参考https://ict119.com/unity_admob_error/

AndroidビルドでError: Error while saving blame file, build will continueエラー

Assets/Plugins/Android/AndroidManifest.xml のxmlns:toolsがなければ追加

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.unity3d.player"
    android:installLocation="preferExternal"
    android:versionCode="1"
    android:versionName="1.0">

READ_PHONE_STATE権限が追加される問題

READ_PHONE_STATEを追加するとよいとあったがREAD_PHONE_STATEの権限は消えなかった。

Assets/Plugins/Android/AndroidManifest.xml

<uses-permission android:name="android.permission.READ_PHONE_STATE" tools:node="remove" />

https://teratail.com/questions/95477

に書いてる通り、toolsを25.2.5に変更するとREAD_PHONE_STATE権限が消えた。(2017.1.1.f1で確認)

(Unity2018.3.6.f1だと起動時に"SDK Tools version 25.2.5 < 26.1.1."がでて26.1.1に更新される)

参考:https://teratail.com/questions/95477

参考:https://qiita.com/matsuyoro/items/7a3f133a610c5c8c56d4

参考:https://blog.narumium.net/2018/02/26/%E3%80%90unity%E3%80%91%E5%8B%9D%E6%89%8B%E3%81%ABread_phone_state%E6%A8%A9%E9%99%90%E3%81%8C%E8%BF%BD%E5%8A%A0%E3%81%95%E3%82%8C%E3%82%8B/

複数sceneからAdMobを呼び出す

AdMob.cs

using GoogleMobileAds.Api;
public class AdMob
{
    BannerView bannerView;
    public void Init()
    {
        MobileAds.Initialize(GetAppId());
    }
    string GetAppId() {
    {
        #if UNITY_ANDROID
            string appId = "ca-app-pub-3940256099942544~3347511713";
        #elif UNITY_IPHONE
            string appId = "ca-app-pub-3940256099942544~1458002511";
        #else
            string appId = "unexpected_platform";
        #endif
        return appId;
    }
    string GetAdUnitId() {
        #if UNITY_ANDROID
            string adUnitId = "ca-app-pub-3940256099942544/6300xxxxxx";
        #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/2934xxxxxx";
        #else
            string adUnitId = "unexpected_platform";
        #endif
        return adUnitId;
    }
    public void RequestBanner()
    {
        bannerView = new BannerView(GetAdUnitId(), AdSize.MediumRectangle, AdPosition.Center);
        AdRequest request = new AdRequest.Builder().Build();
        bannerView.LoadAd(request);
    }
    public void RequestBannerBottom()
    {
        bannerView = new BannerView(GetAdUnitId(), AdSize.MediumRectangle, AdPosition.Bottom);
        AdRequest request = new AdRequest.Builder().Build();
        bannerView.LoadAd(request);
    }
    public void Destroy()
    {
        bannerView.Destroy();
        bannerView = null;
    }
}

呼び出す側

AdMob admob;
void Start()
{
    admob = new AdMob();
    admob.Init();
    admob.RequestBanner();
}
void OnClickPlay() {
    admob.Destroy();
    admob = null;
    SceneManager.LoadScene ("PlayScene");
}

複数sceneからAdMobを呼び出す

AdMob.cs

using GoogleMobileAds.Api;
public class AdMob
{
    BannerView bannerView;
    public void Init()
    {
        MobileAds.Initialize(GetAppId());
    }
    string GetAppId() {
    {
        #if UNITY_ANDROID
            string appId = "ca-app-pub-3940256099942544~3347511713";
        #elif UNITY_IPHONE
            string appId = "ca-app-pub-3940256099942544~1458002511";
        #else
            string appId = "unexpected_platform";
        #endif
        return appId;
    }
    string GetAdUnitId() {
        #if UNITY_ANDROID
            string adUnitId = "ca-app-pub-3940256099942544/6300978111";
        #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/2934735716";
        #else
            string adUnitId = "unexpected_platform";
        #endif
        return adUnitId;
    }
    public void RequestBanner()
    {
        bannerView = new BannerView(GetAdUnitId(), AdSize.MediumRectangle, AdPosition.Center);
        AdRequest request = new AdRequest.Builder().Build();
        bannerView.LoadAd(request);
    }
    public void RequestBannerBottom()
    {
        bannerView = new BannerView(GetAdUnitId(), AdSize.MediumRectangle, AdPosition.Bottom);
        AdRequest request = new AdRequest.Builder().Build();
        bannerView.LoadAd(request);
    }
    public void Destroy()
    {
        bannerView.Destroy();
        bannerView = null;
    }
}

呼び出す側

AdMob admob;
void Start()
{
    admob = new AdMob();
    admob.Init();
    admob.RequestBanner();
}
void OnClickPlay() {
    admob.Destroy();
    admob = null;
    SceneManager.LoadScene ("PlayScene");
}

広告が出なくなった時の対応方法

以下どれかでなおるかも

広告idを変更

androidの場合は"設定/google/広告/広告リセット"で広告idをリセットする iPhoneの場合は"設定/プライバシー/adadvitising identifierをリセット"で広告idをリセットする

unity-androidのビルドオプションをminifyからNoneへ変更

UnityのPlayer SettingsのandroidのpublisingSetting/MinifyをProguardからNoneへ

再度unityadmobプラグインを入れる

  1. dllなどが抜けてないか確認
  2. Assets/PlayserviceResolver/AndroidResolver/ForceResolver

D8: Program type already present: com.google.unity.ads.Banner$12エラーが出たら

GoogleMobileAdsのversionを更新したなどででるようであれば、一旦Plugins/AndroidやPlugins/iOSを削除

  • mainTemplate.gradleのフォーマットが変わってた。

アダプティブバナー

320x50の横幅いっぱいのようなレイアウト

サンプル

AdSize adaptiveSize = AdSize.GetCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(AdSize.FullWidth);
bannerView = new BannerView(adUnitId, adaptiveSize, AdPosition.Bottom);
  • AdSize.GetLandscapeAnchoredAdaptiveBannerAdSizeWithWidth(横向き)
  • AdSize.GetPortraitAnchoredAdaptiveBannerAdSizeWithWidth(縦向き)
  • AdSize.GetCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(実行時の向き)

参考:https://developers.google.com/admob/unity/banner/adaptive?hl=ja

広告の高さのサイズを取得

注意:テスト環境でのみ有効で、本番環境では"ADAPTIVE(Clone)"のGameObjectが取得できないので、使えなかった。

bannerView.OnBannerAdLoaded += () =>
{
	GameObject adaptive = GameObject.Find("ADAPTIVE(Clone)");
	float scale = adaptive.transform.localScale.y;
	float adaptiveAdHeight = scale * bannerView.GetHeightInPixels();
        Debug.Log($"ad loaded height: {adaptiveAdHeight}");
};

出力

bannerView.GetHeightInPixels()=100 
height=169.1667

参考:https://stackoverflow.com/questions/77169439/get-admob-adaptive-banner-height-on-unity

広告の高さのサイズをfitさせる例

[SerializeField] RectTransform contentImage;
private AdMobBanner admobBanner;
private void RequestAdmobBanner()
{
	admobBanner = new AdMobBanner();
	admobBanner.Init();
	System.Action<float> callback = (float adaptiveAdHeight) =>
	{
		AdjustContentBottom(adaptiveAdHeight);
	};
	admobBanner.RequestAdaptiveBanner(callback);
}
// imageのstretchのbottom更新
private void AdjustContentBottom(float bottom)
{
	if (contentImage != null)
	{
		Vector2 offset = contentImage.offsetMin;
		offset.y = bottom;
		contentImage.offsetMin = offset;
	}
}

AdMobBanner.cs

public void RequestAdaptiveBanner(System.Action<float> callback = null)
{
	AdSize adaptiveSize = AdSize.GetCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(AdSize.FullWidth);
	bannerView = new BannerView(GetAdUnitId(), adaptiveSize, AdPosition.Bottom);
	bannerView.OnBannerAdLoaded += () =>
	{
		GameObject adaptive = GameObject.Find("ADAPTIVE(Clone)");
		float scale = adaptive.transform.localScale.y;
		adaptiveAdHeight = scale * bannerView.GetHeightInPixels();
		// Debug.Log($"ad loaded height: {adaptiveAdHeight}");
		callback(adaptiveAdHeight);
	};
	bannerView.LoadAd(request);
}

広告の高さのサイズをfitさせる例(LayoutElementの場合)

LayoutElement layoutElement = footAdObj.GetComponent<LayoutElement>();
if (layoutElement != null)
{
	float space = 10f;
	CanvasScaler canvasScaler = canvas.GetComponent<CanvasScaler>();
	float scaleFactor = Mathf.Min(
		Screen.width / canvasScaler.referenceResolution.x,
		Screen.height / canvasScaler.referenceResolution.y
	);
        layoutElement.minHeight = adaptiveAdHeight / scaleFactor + space;
	// Debug.Log("scaleFactor layoutElement.minHeight=" + layoutElement.minHeight);
}

canvasScalerを使ってない場合は、scaleFactorじゃなくて、canvas.transform.localScale.yを使う。