Unity游戏项目接广告

Unity游戏项目中接入GoogleAdMob

先看效果图

接入测试横幅广告,代码如下:

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

public class GoogleAdMobManager : MonoBehaviour
{
    private static GoogleAdMobManager _instance;  

     public static GoogleAdMobManager Instance  
    {  
        get  
        {  
            if (_instance == null)  
            {  
                // 尝试在场景中找到GoogleAdMobManager实例  
                _instance = FindObjectOfType<GoogleAdMobManager>();  
  
                if (_instance == null)  
                {  
                    Debug.LogError("GoogleAdMobManager instance not found in the scene!");  
                }  
            }  
            return _instance;  
        }  
    }  

    private void Awake()  
    {  
        // 确保不会创建GoogleAdMobManager的多个实例  
        if (_instance != null && _instance != this)  
        {  
            Destroy(gameObject);  
            return;  
        }  
          
        _instance = this;  
        DontDestroyOnLoad(gameObject); // 防止在加载新场景时销毁此对象(可选)  
    }  

    void Start()
    {
        MobileAds.Initialize((InitializationStatus initStatus) =>
        {
            CreateBannerView();  
            LoadAd();  
            ListenToAdEvents(); 

            // LoadInterstitialAd();           
          
        });
    }

    // Update is called once per frame
    void Update()
    {
        
    }


    #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;

  /// <summary>
  /// Creates a 320x50 banner view 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)
      {
          DestroyBannerView();
      }

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

  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);
}

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());
    };
    // 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 DestroyBannerView()
{
    if (_bannerView != null)
    {
        Debug.Log("Destroying banner view.");
        _bannerView.Destroy();
        _bannerView = null;
    }
}


}

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


public class GameMgr : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void OnPlayButtonClick()
    {           
       SceneManager.LoadScene("02-Play");     
       GoogleAdMobManager.Instance?.DestroyBannerView(); 
       
    }

    public void JumpButtonClick()
    {           
       SceneManager.LoadScene("03-RewardAd");     
       
       
    }

    public void OnPauseButtonClick()
    {
        //暂停广告
        //展示广告
        LoadInterstitialAd();
    }

    private InterstitialAd _interstitialAd;  
    private  string _adUnitId = "ca-app-pub-3940256099942544/1033173712";
    
   
    public void LoadInterstitialAd()
    {
        if (_interstitialAd != null)
      {
            _interstitialAd.Destroy();
            _interstitialAd = null;
      } 
        Debug.Log("Loading the interstitial ad.");

    
       // InterstitialAd ad = new interstitialAd(_adUnitId);
        AdRequest adRequest = new AdRequest();

        InterstitialAd.Load(_adUnitId, 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;
          });

          ShowInterstitialAd();

    }


    public void ShowInterstitialAd()
{
    if (_interstitialAd != null && _interstitialAd.CanShowAd())
    {
        Debug.Log("Showing interstitial ad.");
        _interstitialAd.Show();
    }
    else
    {
        Debug.LogError("Interstitial ad is not ready yet.");
    }
}

}

场景1,MainCamera上挂载上面两个脚本,GoogleAdMobManager .cs和 GameMgr.cs

创建StartButton按钮

场景2,加载插屏广告InterstitialAd,Main Camera上挂载Game Mgr.cs

创建Pause Game按钮,当暂停的时候,显示插屏广告,调用Game Mgr.cs中OnPauseButtonClick()方法

创建Jump to reward ad,点击跳转到激励广告。点击JumpButton触发GameMgr中JumpButtonClick()方法。

场景2,02-play中的Main Camera上的Audio Listener需去除,项目场景中只能有一个Audio Listener

场景3,加载激励广告

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

public class RewardAd : MonoBehaviour
{
    

    #if UNITY_ANDROID
        private string _adUnitId = "ca-app-pub-3940256099942544/5224354917";
    #elif UNITY_IPHONE
        private string _adUnitId = "ca-app-pub-3940256099942544/1712485313";
    #else
        private string _adUnitId = "unused";
    #endif

  private RewardedAd _rewardedAd;



    void Start()
    {
        MobileAds.Initialize((InitializationStatus initStatus) =>
        {
            LoadRewardedAd();
            
        });
        
    }



    public void LoadRewardedAd()
    {
        // Clean up the old ad before loading a new one.
        if (_rewardedAd != null)
        {
                _rewardedAd.Destroy();
                _rewardedAd = null;
        }

        Debug.Log("Loading the rewarded ad.");

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

        // send the request to load the ad.
        RewardedAd.Load(_adUnitId, 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;
            });

            ShowRewardedAd();
    }

public void ShowRewardedAd()
{
    const string rewardMsg =
        "Rewarded ad rewarded the user. Type: {0}, amount: {1}.";

    if (_rewardedAd != null && _rewardedAd.CanShowAd())
    {
        _rewardedAd.Show((Reward reward) =>
        {
            // TODO: Reward the user.
            Debug.Log(String.Format(rewardMsg, reward.Type, reward.Amount));
        });
    }
}

public void DestroyRewardedAd()
{
    if (_rewardedAd != null)
    {
        Debug.Log("Destroying rewardedAd view.");
        _rewardedAd.Destroy();
        _rewardedAd = null;
    }
}



}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/465896.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

观察者模式的理解和引用

1.前言 在之前的H5小游戏中&#xff0c;对于长连接发送的不同类型数据包的处理&#xff0c;是通过switch语句进行处理的&#xff0c;于是在自己的代码中出现了大量的case分支&#xff0c;不方便进行维护和后期的版本迭代。于是在老师的指导下&#xff0c;开始寻求使用观察者模…

【深度学习】滴滴出行-交通场景目标检测

案例5&#xff1a;滴滴出行-交通场景目标检测 相关知识点&#xff1a;目标检测、开源框架的配置和使用&#xff08;mmdetection, mmcv&#xff09; 1 任务目标 1.1 任务和数据简介 本次案例将使用深度学习技术来完成城市交通场景下的目标检测任务&#xff0c;案例所使用的数…

CentOS7 安装ErLang语言环境

在线搜索适合当前linux系统的epel在线安装。 yum -y install epel-release下载erlang-solutions安装包。 wget https://packages.erlang-solutions.com/erlang-solutions-1.0-1.noarch.rpm离线安装erlang-solutions安装包。 rpm -Uvh erlang-solutions-1.0-1.noarch.rpm在线…

项目性能优化—使用JMeter压测SpringBoot项目

项目性能优化—使用JMeter压测SpringBoot项目 我们的压力测试架构图如下&#xff1a; 配置JMeter 在JMeter的bin目录&#xff0c;双击jmeter.bat 新建一个测试计划&#xff0c;并右键添加线程组&#xff1a; 进行配置 一共会发生4万次请求。 ctrl s保存&#xff1b; 添加h…

Aigtek电压放大器的作用及优点是什么

电压放大器是电子技术领域中重要的设备&#xff0c;其作用是将输入信号的电压放大到所需的输出电压水平。电压放大器具有多种优点&#xff0c;下面安泰电子将详细介绍其作用及主要优点。 电压放大器的主要作用是增加信号的电压幅值。通过放大信号的电压&#xff0c;可以增强信号…

网络架构层_服务器上下行宽带

网络架构层_服务器上下行宽带 解释一 云服务器ECS网络带宽的概念、计费、安全及使用限制_云服务器 ECS(ECS)-阿里云帮助中心 网络带宽是指在单位时间&#xff08;一般指的是1秒钟&#xff09;内能传输的数据量&#xff0c;带宽数值越大表示传输能力越强&#xff0c;即在单位…

就业班 2401--3.13 走进网络

走进网络 长风破浪会有时&#xff0c;直挂云帆济沧海。 1.认识计算机 1.计算机网络是由计算机和通讯构成的&#xff0c;网络研究的是“通信”。 ------1946 世界上第一台计算机 2.终端&#xff1a;只有输入和输出功能&#xff0c;没有计算和处理功能。 3.数据&#xff1a;一串…

深入浅出Go的`encoding/xml`库:实战开发指南

深入浅出Go的encoding/xml库&#xff1a;实战开发指南 引言基本概念XML简介Go语言中的XML处理结构体标签&#xff08;Struct Tags&#xff09; 解析XML数据使用xml.Unmarshal解析XML结构体标签详解处理常见解析问题 生成XML数据使用xml.Marshal生成XML使用xml.MarshalIndent优化…

Linux服务器磁盘更改挂载目录

linux服务器磁盘弹性扩容时&#xff0c;会出现没有挂载到理想的目录下&#xff0c;这时候就需要通过命令从新挂载目录&#xff0c;以下示例是把默认挂载目录/home更改为/data 1,df -lh ####查看现有挂载信息 2.lsblk ###查看文件形式&#xff0c;确保原有数据盘文件结构。 3.…

团队如何限制合适的在制品(WIP)数量?

看板之父David Anderson曾说过“看板的本质是一个很朴素的思想&#xff1a;在制品必须被限制。”但对于团队来说&#xff0c;确定一个合适的在制品限制可能是件棘手的事。 在《看板快速启动指南》一文中&#xff0c;我们已经初步了解如何打造一个看板&#xff0c;今天我们来一…

java学习之路-方法讲解

目录 1.方法概念及使用 1.1什么是方法 1.2方法定义 1.3 方法调用的执行过程 1.4 实参和形参的关系(重要) 1.5 没有返回值的方法 2.方法重载 3.方法递归 3.1递归概念 3.2递归执行过程分析 3.3递归练习 代码示例1 代码示例2 1.方法概念及使用 1.1什么是方法 方法就是…

jetson nano——编译一些包的网址导航,pyside2,qt(持续更新)

目录 1.PySide2下载地址2.tesserocr下载地址3.Qt下载地址4.OpenSSL官网5.latex编译器下载地址5.1MikTex5.2TeX Live 1.PySide2下载地址 https://download.qt.io/official_releases/QtForPython/pyside2/ 如下图&#xff1a; 2.tesserocr下载地址 https://github.com/simonflue…

python网络编程:通过socket实现TCP客户端和服务端

目录 写在开头 socket服务端&#xff08;基础&#xff09; socket客户端&#xff08;基础&#xff09; 服务端实现&#xff08;可连接多个客户端&#xff09; 客户端实现 数据收发效果 写在开头 近期可能会用python实现一些网络安全工具&#xff0c;涉及到许多关于网络…

PythonWeb——Django框架

框架介绍 1.什么是框架? 框架就是程序的骨架&#xff0c;主体结构&#xff0c;也是个半成品。 2.框架的优缺点 可重用、成熟,稳健、易扩展、易维护 3.Python中常见的框架 大包大揽 Django被官方称之为完美主义者的Web框架。力求精简web.py和Tornado新生代微框架Flask和B…

hadoop分布式环境ssh设置免密登陆之后目标主机更换无法连接解决

在进行hadoop分布式环境搭建时&#xff08;三台机&#xff0c;master&#xff0c;slave1&#xff0c;slave2&#xff09;&#xff0c;后期slave2系统出现问题&#xff0c;更换新机后&#xff0c;master与slave2文件传输失败&#xff1a; 以为是秘钥过期的问题&#xff0c;更换…

【Linux】一文解决如何在终端查看 python解释器 的位置

【Linux】一文解决如何在终端查看 python解释器 的位置 &#x1f308; 个人主页&#xff1a;高斯小哥 &#x1f525; 高质量专栏&#xff1a;Matplotlib之旅&#xff1a;零基础精通数据可视化、Python基础【高质量合集】、PyTorch零基础入门教程&#x1f448; 希望得到您的订阅…

Github主页设置贪吃蛇详细教程

先看最终实现结果&#xff1a; 有条贪吃蛇放在主页还是蛮酷的哈哈哈。接下来我来讲一讲怎么在Github主页添加一条贪吃蛇。 首先要修改自己的Github的主页&#xff0c;我们得有一个特殊的仓库——这个仓库必须与你的Github用户名保持一致&#xff0c;并且需要公开&#xff0c…

静默快速安装oracle 19c

静默快速安装oracle 19c 1.配置yum源 1.配置网络yum源 1.删除redhat7.0系统自带的yum软件包&#xff1b; rpm -qa|grep yum >oldyum.pkg 备份原信息rpm -qa|grep yum|xargs rpm -e --nodeps 不检查依赖&#xff0c;直接删除rpm包 1232.自行下载所需要的软件包。包名会…

求解3、4、6自由度仿射变换矩阵

说明&#xff1a;一开始将目光放在了opencv上&#xff0c;发现只有4、6自由度的仿射变换求解&#xff0c;后来发现skimage十分强大。 注&#xff1a;美中不足的是&#xff0c;skimage的实现没有RANSAC。 function&#xff1a;skimage.transform.estimate_transform() ttypeeu…

【SpringMVC】SpringMVC的整体执行流程

概述&#xff1a;MVC是一种设计模式&#xff0c;SpringMVC是按照MVC模式实现的优秀框架&#xff0c;可以帮助我们更简洁的完成Web开发&#xff0c;并且天然与Spring集成。后端项目分为Service层&#xff08;处理业务&#xff09;、Dao层&#xff08;数据库操作&#xff09;、En…
最新文章