unity---接入Admob

目录

1.Admob SDK 下载地址

2.将下载好的unityPackage sdk导入到unity里

​编辑

 3.解析依赖到项目中

4.设置admob app ID

 5.android 测试Id

 6.IOS 测试ID

 7.测试 app ID

8. SDK初始化与使用示例代码

9.gradle 配置

10. gradle 下载地址


1.Admob SDK 下载地址

Admob SDK 下载地址

2.将下载好的unityPackage sdk导入到unity里

在 Unity 编辑器中打开您的项目,然后依次选择 Assets > Import Package > Custom Package,并找到您下载的 GoogleMobileAdsPlugin.unitypackage 文件。

 3.解析依赖到项目中

在 Unity 编辑器中,依次选择 Assets > External Dependency Manager > Android Resolver > Resolve。Unity 外部依赖项管理器库会将声明的依赖项复制到 Unity 应用的 Assets/Plugins/Android 目录中。

4.设置admob app ID

在 Unity 编辑器中,从菜单中依次选择 Assets > Google Mobile Ads > Settings

 5.android 测试Id

 6.IOS 测试ID

 7.测试 app ID

ca-app-pub-3940256099942544~3347511713

8. SDK初始化与使用示例代码

using UnityEngine;
using GoogleMobileAds.Api;
using System;
using GoogleMobileAds.Common;
using System.Collections.Generic;
using UnityEngine.Events;
using UnityEngine.UI;

public class AdsContr : Singleton<AdsContr>
{
    private readonly TimeSpan APPOPEN_TIMEOUT = TimeSpan.FromHours(4);
    private DateTime appOpenExpireTime;

    private AppOpenAd appOpenAd;
    private BannerView bannerView;
    private InterstitialAd interstitialAd;
    private RewardedAd rewardedAd;
    private RewardedInterstitialAd rewardedInterstitialAd;
    /*
    public UnityEvent OnAdLoadedEvent;
    public UnityEvent OnAdFailedToLoadEvent;
    public UnityEvent OnAdOpeningEvent;
    public UnityEvent OnAdFailedToShowEvent;
    public UnityEvent OnUserEarnedRewardEvent;
    public UnityEvent OnAdClosedEvent;
    */

    //Admob测试id ca-app-pub-3940256099942544~3347511713
    private const string open_android_test = "ca-app-pub-3940256099942544/3419835294";
    private const string open_ios_test = "ca-app-pub-3940256099942544/5662855259";
    private const string banner_android_test = "ca-app-pub-3940256099942544/6300978111";
    private const string banner_ios_test = "ca-app-pub-3940256099942544/2934735716";
    private const string interstitial_android_test = "ca-app-pub-3940256099942544/1033173712";
    private const string interstitial_ios_test = "ca-app-pub-3940256099942544/4411468910";
    private const string video_android_test = "ca-app-pub-3940256099942544/5224354917";
    private const string video_ios_test = "ca-app-pub-3940256099942544/1712485313";
    private const string video_interstitial_android_test = "ca-app-pub-3940256099942544/5354046379";
    private const string video_interstitial_ios_test = "ca-app-pub-3940256099942544/6978759866";

    //admob 正式id ca-app-pub-1111111111~222222222 
    private const string open_android = "";
    private const string open_ios = "";
    private const string banner_android = "";
    private const string banner_ios = "";
    private const string interstitial_android = "";
    private const string interstitial_ios = "";
    private const string video_android = "ca-app-pub-11111111/22222222";
    private const string video_ios = "";

    public Text statusText;
    public bool isTest; //是否为测试模式

    private void Start()
    {
        if (!isTest)
        {
            //广告线程与unity主线程同步
            MobileAds.RaiseAdEventsOnUnityMainThread = true;

            //添加测试机
            /*
            List<String> deviceIds = new List<String>() { AdRequest.TestDeviceSimulator };
    #if UNITY_ANDROID
            deviceIds.Add("86BF82E91DB5A2AE32FB942B2B179E9F");
    #elif UNITY_IPHONE
                MobileAds.SetiOSAppPauseOnBackground(true);
                 deviceIds.Add("");
    #endif
            RequestConfiguration requestConfiguration =
                new RequestConfiguration.Builder()
                .SetTagForChildDirectedTreatment(TagForChildDirectedTreatment.Unspecified)
                .SetTestDeviceIds(deviceIds).build();
            MobileAds.SetRequestConfiguration(requestConfiguration);
            */

            //初始化
            MobileAds.Initialize((InitializationStatus obj) =>
            {
                Debug.Log("sdk init success");

                MobileAdsEventExecutor.ExecuteInUpdate(() =>
                {
                    //LoadBanner();
                    //RequestInterstitial();
                    RequestAndLoadRewardedAd();
                    //RequestAndLoadAppOpenAd();
                });
            });

            //AppStateEventNotifier.AppStateChanged += OnAppStateChanged;
        }
    }

    private AdRequest CreateAdRequest()
    {
        return new AdRequest.Builder()
            .AddKeyword("unity-admob-game")
            .Build();
    }

    #region--------Banner Ads--------------------------------------------------
    public void RequestBannerAd()
    {
        PrintStatus("Requesting Banner ad.");
        string adUnitId;
        if (isTest)
        {
#if UNITY_EDITOR
            adUnitId = "unused";
#elif UNITY_ANDROID
        adUnitId = banner_android_test;
#elif UNITY_IPHONE
        adUnitId = banner_ios_test;
#else
        adUnitId = "unexpected_platform";
#endif
        }
        else
        {
#if UNITY_EDITOR
            adUnitId = "unused";
#elif UNITY_ANDROID
        adUnitId = banner_android;
#elif UNITY_IPHONE
        adUnitId = banner_ios;
#else
        adUnitId = "unexpected_platform";
#endif
        }

        // Clean up banner before reusing
        if (bannerView != null)
        {
            bannerView.Destroy();
        }

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

        // Add Event Handlers
        bannerView.OnBannerAdLoaded += () =>
        {
            PrintStatus("Banner ad loaded.");
            //OnAdLoadedEvent.Invoke();
        };
        bannerView.OnBannerAdLoadFailed += (LoadAdError error) =>
        {
            PrintStatus("Banner ad failed to load with error: " + error.GetMessage());
            //OnAdFailedToLoadEvent.Invoke();
        };
        bannerView.OnAdImpressionRecorded += () =>
        {
            PrintStatus("Banner ad recorded an impression.");
        };
        bannerView.OnAdClicked += () =>
        {
            PrintStatus("Banner ad recorded a click.");
        };
        bannerView.OnAdFullScreenContentOpened += () =>
        {
            PrintStatus("Banner ad opening.");
            //OnAdOpeningEvent.Invoke();
        };
        bannerView.OnAdFullScreenContentClosed += () =>
        {
            PrintStatus("Banner ad closed.");
            //OnAdClosedEvent.Invoke();
        };
        bannerView.OnAdPaid += (AdValue adValue) =>
        {
            string msg = string.Format("{0} (currency: {1}, value: {2}",
                                        "Banner ad received a paid event.",
                                        adValue.CurrencyCode,
                                        adValue.Value);
            PrintStatus(msg);
        };

        // Load a banner ad
        bannerView.LoadAd(CreateAdRequest());
    }

    public void DestroyBannerAd()
    {
        if (bannerView != null)
        {
            bannerView.Destroy();
        }
    }
    #endregion

    #region --------Interstitial Ads--------------------------------------------
    public void RequestAndLoadInterstitialAd()
    {
        PrintStatus("Requesting Interstitial ad.");
        string adUnitId;
        if (isTest)
        {
#if UNITY_EDITOR
            adUnitId = "unused";
#elif UNITY_ANDROID
        adUnitId = interstitial_android_test;
#elif UNITY_IPHONE
        adUnitId = interstitial_ios_test;
#else
        adUnitId = "unexpected_platform";
#endif
        }
        else
        {
#if UNITY_EDITOR
            adUnitId = "unused";
#elif UNITY_ANDROID
        adUnitId = interstitial_android;
#elif UNITY_IPHONE
        adUnitId = interstitial_ios;
#else
        adUnitId = "unexpected_platform";
#endif
        }

        // Clean up interstitial before using it
        if (interstitialAd != null)
        {
            interstitialAd.Destroy();
        }

        // Load an interstitial ad
        InterstitialAd.Load(adUnitId, CreateAdRequest(),
            (InterstitialAd ad, LoadAdError loadError) =>
            {
                if (loadError != null)
                {
                    PrintStatus("Interstitial ad failed to load with error: " +
                        loadError.GetMessage());
                    return;
                }
                else if (ad == null)
                {
                    PrintStatus("Interstitial ad failed to load.");
                    return;
                }

                PrintStatus("Interstitial ad loaded.");
                interstitialAd = ad;

                ad.OnAdFullScreenContentOpened += () =>
                {
                    PrintStatus("Interstitial ad opening.");
                    //OnAdOpeningEvent.Invoke();
                };
                ad.OnAdFullScreenContentClosed += () =>
                {
                    PrintStatus("Interstitial ad closed.");
                    //OnAdClosedEvent.Invoke();
                };
                ad.OnAdImpressionRecorded += () =>
                {
                    PrintStatus("Interstitial ad recorded an impression.");
                };
                ad.OnAdClicked += () =>
                {
                    PrintStatus("Interstitial ad recorded a click.");
                };
                ad.OnAdFullScreenContentFailed += (AdError error) =>
                {
                    PrintStatus("Interstitial ad failed to show with error: " +
                                error.GetMessage());
                };
                ad.OnAdPaid += (AdValue adValue) =>
                {
                    string msg = string.Format("{0} (currency: {1}, value: {2}",
                                               "Interstitial ad received a paid event.",
                                               adValue.CurrencyCode,
                                               adValue.Value);
                    PrintStatus(msg);
                };
            });
    }

    public void ShowInterstitialAd()
    {
        if (interstitialAd != null && interstitialAd.CanShowAd())
        {
            interstitialAd.Show();
        }
        else
        {
            PrintStatus("Interstitial ad is not ready yet.");
        }
    }

    public void DestroyInterstitialAd()
    {
        if (interstitialAd != null)
        {
            interstitialAd.Destroy();
        }
    }
    #endregion

    #region --------open Ads----------------------------------------------------
    public bool IsAppOpenAdAvailable
    {
        get
        {
            return (appOpenAd != null && appOpenAd.CanShowAd() && DateTime.Now < appOpenExpireTime);
        }
    }

    public void OnAppStateChanged(AppState state)
    {
        Debug.Log("App State is " + state);
        MobileAdsEventExecutor.ExecuteInUpdate(() =>
        {
            if (state == AppState.Foreground)
            {
                ShowAppOpenAd();
            }
        });
    }

    public void RequestAndLoadAppOpenAd()
    {
        PrintStatus("Requesting App Open ad.");
        string adUnitId;
        if (isTest)
        {
#if UNITY_EDITOR
            adUnitId = "unused";
#elif UNITY_ANDROID
        adUnitId = open_android_test;
#elif UNITY_IPHONE
        adUnitId = open_ios_test;
#else
        adUnitId = "unexpected_platform";
#endif
        }
        else
        {
#if UNITY_EDITOR
            adUnitId = "unused";
#elif UNITY_ANDROID
        adUnitId = open_android;
#elif UNITY_IPHONE
        adUnitId = open_ios;
#else
        adUnitId = "unexpected_platform";
#endif
        }
        // destroy old instance.
        if (appOpenAd != null)
        {
            DestroyAppOpenAd();
        }

        // Create a new app open ad instance.
        AppOpenAd.Load(adUnitId, ScreenOrientation.Portrait, CreateAdRequest(),
            (AppOpenAd ad, LoadAdError loadError) =>
            {
                if (loadError != null)
                {
                    PrintStatus("App open ad failed to load with error: " +
                        loadError.GetMessage());
                    return;
                }
                else if (ad == null)
                {
                    PrintStatus("App open ad failed to load.");
                    return;
                }

                PrintStatus("App Open ad loaded. Please background the app and return.");
                this.appOpenAd = ad;
                this.appOpenExpireTime = DateTime.Now + APPOPEN_TIMEOUT;

                ad.OnAdFullScreenContentOpened += () =>
                {
                    PrintStatus("App open ad opened.");
                    //OnAdOpeningEvent.Invoke();
                };
                ad.OnAdFullScreenContentClosed += () =>
                {
                    PrintStatus("App open ad closed.");
                    //OnAdClosedEvent.Invoke();
                };
                ad.OnAdImpressionRecorded += () =>
                {
                    PrintStatus("App open ad recorded an impression.");
                };
                ad.OnAdClicked += () =>
                {
                    PrintStatus("App open ad recorded a click.");
                };
                ad.OnAdFullScreenContentFailed += (AdError error) =>
                {
                    PrintStatus("App open ad failed to show with error: " +
                        error.GetMessage());
                };
                ad.OnAdPaid += (AdValue adValue) =>
                {
                    string msg = string.Format("{0} (currency: {1}, value: {2}",
                                               "App open ad received a paid event.",
                                               adValue.CurrencyCode,
                                               adValue.Value);
                    PrintStatus(msg);
                };
            });
    }

    public void DestroyAppOpenAd()
    {
        if (this.appOpenAd != null)
        {
            this.appOpenAd.Destroy();
            this.appOpenAd = null;
        }
    }

    public void ShowAppOpenAd()
    {
        if (!IsAppOpenAdAvailable)
        {
            return;
        }
        appOpenAd.Show();
    }
    #endregion

    #region--------reward Ads--------------------------------------------------
    public void RequestAndLoadRewardedAd()
    {
        string adUnitId;
        PrintStatus("Requesting Rewarded ad.");
        if (isTest)
        {
#if UNITY_EDITOR
            adUnitId = "unused";
#elif UNITY_ANDROID
        adUnitId = video_android_test;
#elif UNITY_IPHONE
        adUnitId = video_ios_test;
#else
        adUnitId = "unexpected_platform";
#endif
        }
        else
        {
#if UNITY_EDITOR
            adUnitId = "unused";
#elif UNITY_ANDROID
        adUnitId = video_android;
#elif UNITY_IPHONE
        adUnitId = video_ios;
#else
        adUnitId = "unexpected_platform";
#endif
        }

        // create new rewarded ad instance
        RewardedAd.Load(adUnitId, CreateAdRequest(),
            (RewardedAd ad, LoadAdError loadError) =>
            {
                if (loadError != null)
                {
                    PrintStatus("Rewarded ad failed to load with error: " +
                                loadError.GetMessage());
                    return;
                }
                else if (ad == null)
                {
                    PrintStatus("Rewarded ad failed to load.");
                    return;
                }

                PrintStatus("Rewarded ad loaded.");
                rewardedAd = ad;

                ad.OnAdFullScreenContentOpened += () =>
                {
                    PrintStatus("Rewarded ad opening.");
                    //OnAdOpeningEvent.Invoke();
                };
                ad.OnAdFullScreenContentClosed += () =>
                {
                    PrintStatus("Rewarded ad closed.");
                    //OnAdClosedEvent.Invoke();
                };
                ad.OnAdImpressionRecorded += () =>
                {
                    PrintStatus("Rewarded ad recorded an impression.");
                };
                ad.OnAdClicked += () =>
                {
                    PrintStatus("Rewarded ad recorded a click.");
                };
                ad.OnAdFullScreenContentFailed += (AdError error) =>
                {
                    PrintStatus("Rewarded ad failed to show with error: " +
                               error.GetMessage());
                };
                ad.OnAdPaid += (AdValue adValue) =>
                {
                    string msg = string.Format("{0} (currency: {1}, value: {2}",
                                               "Rewarded ad received a paid event.",
                                               adValue.CurrencyCode,
                                               adValue.Value);
                    PrintStatus(msg);
                };
            });
    }

    public void ShowRewardedAd(Action act)
    {
        if (isTest)
        {
            act();
        }
        else
        {
            if (rewardedAd != null)
            {
                rewardedAd.Show((Reward reward) =>
                {
                    act();
                    PrintStatus("Rewarded ad granted a reward: " + reward.Amount);
                    RequestAndLoadRewardedAd();
                });
            }
            else
            {
                PrintStatus("Rewarded ad is not ready yet.");
                RequestAndLoadRewardedAd();
            }
        }
    }
    #endregion

    #region--------reward Interstitial Ads-------------------------------------
    public void RequestAndLoadRewardedInterstitialAd()
    {
        PrintStatus("Requesting Rewarded Interstitial ad.");
#if UNITY_EDITOR
        string adUnitId = "unused";
#elif UNITY_ANDROID
            string adUnitId = video_interstitial_android_test;
#elif UNITY_IPHONE
            string adUnitId = video_interstitial_ios_test;
#else
            string adUnitId = "unexpected_platform";
#endif

        // Create a rewarded interstitial.
        RewardedInterstitialAd.Load(adUnitId, CreateAdRequest(),
            (RewardedInterstitialAd ad, LoadAdError loadError) =>
            {
                if (loadError != null)
                {
                    PrintStatus("Rewarded interstitial ad failed to load with error: " +
                                loadError.GetMessage());
                    return;
                }
                else if (ad == null)
                {
                    PrintStatus("Rewarded interstitial ad failed to load.");
                    return;
                }

                PrintStatus("Rewarded interstitial ad loaded.");
                rewardedInterstitialAd = ad;

                ad.OnAdFullScreenContentOpened += () =>
                {
                    PrintStatus("Rewarded interstitial ad opening.");
                    //OnAdOpeningEvent.Invoke();
                };
                ad.OnAdFullScreenContentClosed += () =>
                {
                    PrintStatus("Rewarded interstitial ad closed.");
                    //OnAdClosedEvent.Invoke();
                };
                ad.OnAdImpressionRecorded += () =>
                {
                    PrintStatus("Rewarded interstitial ad recorded an impression.");
                };
                ad.OnAdClicked += () =>
                {
                    PrintStatus("Rewarded interstitial ad recorded a click.");
                };
                ad.OnAdFullScreenContentFailed += (AdError error) =>
                {
                    PrintStatus("Rewarded interstitial ad failed to show with error: " +
                                error.GetMessage());
                };
                ad.OnAdPaid += (AdValue adValue) =>
                {
                    string msg = string.Format("{0} (currency: {1}, value: {2}",
                                                "Rewarded interstitial ad received a paid event.",
                                                adValue.CurrencyCode,
                                                adValue.Value);
                    PrintStatus(msg);
                };
            });
    }

    public void ShowRewardedInterstitialAd()
    {
        if (rewardedInterstitialAd != null)
        {
            rewardedInterstitialAd.Show((Reward reward) =>
            {
                PrintStatus("Rewarded interstitial granded a reward: " + reward.Amount);
            });
        }
        else
        {
            PrintStatus("Rewarded interstitial ad is not ready yet.");
        }
    }
    #endregion
    ///<summary>
    /// Log the message and update the status text on the main thread.
    ///<summary>
    private void PrintStatus(string message)
    {
        if (isTest)
        {
            Debug.Log(message);
            MobileAdsEventExecutor.ExecuteInUpdate(() =>
            {
                statusText.text = message;
            });
        }
    }
}

9.gradle 配置

allprojects {
    repositories {
        maven { url 'https://dl.google.com/dl/android/maven2/' }
        google()
        maven { url "https://jitpack.io" }
        maven { url 'https://maven.aliyun.com/repository/jcenter' }
        jcenter()
       
        flatDir {
            dirs 'libs'
        }
        mavenLocal()
        maven {
            url "https://maven.aliyun.com/nexus/content/repositories/releases"
        }

    }
}



10. gradle 下载地址

unity 升级gradle版本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

格拉格拉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值