当前位置: 首页 > article >正文

【Unity】Unity中接入Admob聚合广告平台,可通过中介接入 AppLovin,Unity Ads,Meta等渠道的广告

一、下载Google Admob的SDK插件

到Google Admob官网中,切换到Unity平台在这里插入图片描述

进来之后是这样,注意后面有Unity标识,然后点击下载,跳转到github中,下载最新的Admob插件sdk,导入到Unity中在这里插入图片描述

二、阅读官方文档,了解广告加载流程

通过阅读官方文档,我们可以了解到其中有针对各类广告的Ios和Android的测试广告单元id,这对我们刚接入时测试阶段很有必要
在这里插入图片描述

然后我们以激励广告为例,可以看到接入激励广告的详细流程,官方下面也提供了所有流程的详细代码,其实如果没有特殊需求,官方的代码可以直接复制到我们的项目中就能使用
在这里插入图片描述

三、通过中介接入各渠道的广告

通过Admob中的中介就能接入各渠道的广告,当展示广告时候,他们会自动竞价,展示价格最高的广告。这里我们点击图中箭头,就可以下载对应渠道的最新版本的SDK插件,然后导入到Unity中即可,不需要任何设置,聚合平台会自动调取对应的广告渠道进行展示
在这里插入图片描述
下面是我导入到Unity中的所有插件
在这里插入图片描述
好了,到这里前端的准备基本结束了,相关的插件也都导入完毕了,如果是个人做游戏的话,自己到Admob后台注册对应的账号和Appid以及各个广告位的广告id,以及中介平台的各种广告id和相关联的功能,公司做游戏的话,这些各种id让对应的后台运营人员给到自己就好了,这里只介绍前端程序的相关内容,具体的id申请自行到后台操作一下

四、代码接入

该代码仅在测试阶段,通过官方的测试广告单元id全部通过,展示了出来,包括Banner,激励广告,插屏广告,详细内容根据自己的项目而定

using GoogleMobileAds.Api;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AdManager : Singleton<AdManager>
{


    private int sdkInitializedState = -1;//0--unconsent 1--consen

    private string ADMobRewardUnit = "ca-app-pub-3940256099942544/5224354917";
    private string ADMobInterstitialUnit = "ca-app-pub-3940256099942544/1033173712";
    private string ADMobBannerUnit = "ca-app-pub-3940256099942544/6300978111";
	private RewardedAd _rewardedAd = null;
	private InterstitialAd _interstitialAd = null;
    private BannerView _bannerView;

    private int tryInteTimes = 0;
    private int loadInteTimes = 1;

    private int tryTimes = 0;
    private int maxTryTimes = 0;
    private int loadTimes = 1;

    private void Start()
    {
        Init();
    }

    public void Init()
    {
        MobileAds.RaiseAdEventsOnUnityMainThread = true;
        MobileAds.Initialize((InitializationStatus initStatus) =>
        {
            // This callback is called once the MobileAds SDK is initialized.
            sdkInitializedState = 1;
            PrepareRewardAds();
            PrepareInterAds();
        });
    }

    private void PrepareRewardAds()
    {
        if (sdkInitializedState < 0)
            return;
        if (_rewardedAd != null)
        {
            _rewardedAd.Destroy();
            _rewardedAd = null;
        }

        var adRequest = new AdRequest();
        RewardedAd.Load(ADMobRewardUnit, adRequest,
            (RewardedAd ad, LoadAdError error) =>
            {
                // if error is not null, the load request failed.
                if (error != null || ad == null)
                {
                    Debug.LogError("Rewarded ad failed to load an ad with error : " + error);
                    return;
                }

                Debug.Log("Rewarded ad loaded with response : " + ad.GetResponseInfo());

                _rewardedAd = ad;
            });
    }


    private void PrepareInterAds()
    {
        if (sdkInitializedState < 0)
            return;
        if (_interstitialAd != null)
        {
            _interstitialAd.Destroy();
            _interstitialAd = null;
        }

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

        // send the request to load the ad.
        InterstitialAd.Load(ADMobInterstitialUnit, adRequest,
            (InterstitialAd ad, LoadAdError error) =>
            {
                // if error is not null, the load request failed.
                if (error != null || ad == null)
                {
                    Debug.LogError("interstitial ad failed to load an ad with error : " + error);
                    return;
                }

                Debug.Log("Interstitial ad loaded with response : " + ad.GetResponseInfo());

                _interstitialAd = ad;
            });
    }


    [ContextMenu("测试Banner")]
    public void LoadBannerAd()
    {
        // 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>
    /// Creates a 320x50 banner view at top of the screen.
    /// </summary>
    private void CreateBannerView()
    {
        Debug.Log("Creating banner view");

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

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


    [ContextMenu("测试插屏广告")]
    public void ShowInterAD()
    {
        if (_interstitialAd != null && _interstitialAd.CanShowAd())
        {
            // SetAdmobInterstitialListener(_interstitialAd);
            _interstitialAd.Show();
        }
        else
        {
            if (++this.tryInteTimes >= this.maxTryTimes)
            {
                this.loadInteTimes = 3;
                this.PrepareInterAds();
                this.tryInteTimes = 0;
            }
            return;
        }
    }


    public void ShowRewardAD(Action successCallback)
    {
        if (_rewardedAd != null && _rewardedAd.CanShowAd())
        {
            SetAdmobRewardListener(_rewardedAd);
            _rewardedAd.Show((Reward reward) =>
            {
                successCallback();
            });
        }
    }


    private void SetAdmobRewardListener(RewardedAd ad)
    {
        // Raised when a click is recorded for an ad.
        ad.OnAdClicked += () =>
        {
            //RewardedAdClicked();
        };
        // Raised when an ad opened full screen content.
        ad.OnAdFullScreenContentOpened += () =>
        {
            Debug.Log("Rewarded ad full screen content opened.");
        };
        // Raised when the ad closed full screen content.
        ad.OnAdFullScreenContentClosed += () =>
        {
            PrepareRewardAds();
            //RewardedAdClosed();
        };
        // Raised when the ad failed to open full screen content.
        ad.OnAdFullScreenContentFailed += (AdError error) =>
        {
            Debug.LogError("Rewarded ad failed to open full screen content with error : " + error);
            // RewardedAdFailed();
            PrepareRewardAds();
        };
    }

    private void SetAdmobInterstitialListener(InterstitialAd interstitialAd)
    {
        // Raised when a click is recorded for an ad.
        interstitialAd.OnAdClicked += () =>
        {
            Debug.Log("Interstitial ad was clicked.");
            //InterstitialAdClicked();
        };
        // Raised when an ad opened full screen content.
        interstitialAd.OnAdFullScreenContentOpened += () =>
        {
            Debug.Log("Interstitial ad full screen content opened.");
           // InterstitialAdDisplayed();
        };
        // Raised when the ad closed full screen content.
        interstitialAd.OnAdFullScreenContentClosed += () =>
        {
            Debug.Log("Interstitial ad full screen content closed.");
            //InterstitialAdClosed();
            PrepareInterAds();
        };
        // Raised when the ad failed to open full screen content.
        interstitialAd.OnAdFullScreenContentFailed += (AdError error) =>
        {
            Debug.LogError("Interstitial ad failed to open full screen content with error : " + error);
            //InterstitialAdFailed();
            PrepareInterAds();
        };
    }

    [ContextMenu("测试激励广告")]
    public void TestShowRewardAd()
    {
        ShowRewardAD(() => 
        {
            Debug.LogError("激励广告回调");
        });
    }


}

测试方法也在里面,直接挂到Unity实体上运行,右击代码就可以进行测试,展示对应的广告
Over~
看到这里了,觉得有用记得点赞收藏关注哦~


http://www.kler.cn/a/350282.html

相关文章:

  • CPU狂飙900%如何分析?怎么定位?怎么溯源处理
  • STM32 FreeROTS Tickless低功耗模式
  • GS论文阅读--GeoTexDensifier
  • Spring 中的事件驱动模型
  • JupyterLab 安装以及部分相关配置
  • OSI七层协议——分层网络协议
  • 快速理解AUTOSAR CP的软件架构层次以及各层的作用
  • 第三弹:探索网络传输中的TFTP、UDP广播与多播技术
  • 打印杨辉三角形
  • 用Cursor开发了一个图片分割器
  • 观察者模式和发布-订阅模式的区别
  • 汽车结构设计外覆盖件抗凹分析的意义和分类
  • HarmonyOS Next模拟器异常问题及解决方法
  • 信息和介质的辩证
  • 智能化企业新人培训:AI助理如何加速新员融入与成长
  • 遥感图像处理又上大分!加个多模态,一篇A会到手~
  • 洛谷P1484.种树
  • 【Linux】基本认知全套入门
  • docker启动的rabbitmq如何启动其SSL功能
  • 嵌入式中数据库sqlit3基本使用方法与现象
  • 十、结构型(外观模式)
  • Gin框架操作指南02:JSON渲染
  • 利用 Llama 3.1模型 + Dify开源LLM应用开发平台,在你的Windows环境中搭建一套AI工作流
  • 理解前端开发和小程序开发中的 build 和 dev 模式
  • 迪杰斯特拉算法的理解
  • Content-Type 详解