【Unity变现】Unity 接入Unity ADS广告

news2024/10/1 23:48:13

说在前面的话,Unity ADS是Unity官方做的广告变现平台,但广告在我国大陆无法使用,开发时测试的话需要上代理才能看到请求的广告。
如果游戏不准备发布到海外市场,可以不考虑这个平台。

一、注册Unity ADS平台的准备

https://dashboard.unity3d.com/gaming/organizations

注册的Unity账户使用和UnityHub一样的。

注册成功后,在项目中找到与你的Unity工程同名的项目,如果没有则新建

在这里插入图片描述
并且在快捷方式上添加Unity Ads Monetization模块
在这里插入图片描述
点击模块,选择你的项目。启用广告功能。

二、Unity初始化

可以参考https://docs.unity.com/ads/en-us/manual/CreatingUnityProjects官方文档进行操作。

1.安装SDK

在 Unity 编辑器中,选择 Window > Package Manager。
在“包管理器”窗口中,从列表中选择“Advertisement Legacy”包,然后选择最新验证的版本。

2.设置SDK

在编辑器中选择Edit>ProjectSettings
找到Services>Ads 将点击右侧的OFF,将状态改为ON(开启状态)
初次进入界面会提示没有连接到服务器项目之类,在下方选择你在网站上已有或新创建的项目。
并添加GameID(在网页的设置里)
在这里插入图片描述
在这里插入图片描述

3.代码初始化SDK

using UnityEngine;
using UnityEngine.Advertisements;
 
public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener
{
    [SerializeField] string _androidGameId;
    [SerializeField] string _iOSGameId;
    [SerializeField] bool _testMode = true;
    private string _gameId;
 
    void Awake()
    {
        InitializeAds();
    }
 
    public void InitializeAds()
    {
    #if UNITY_IOS
            _gameId = _iOSGameId;
    #elif UNITY_ANDROID
            _gameId = _androidGameId;
    #elif UNITY_EDITOR
            _gameId = _androidGameId; //Only for testing the functionality in the Editor
    #endif
        if (!Advertisement.isInitialized && Advertisement.isSupported)
        {
            Advertisement.Initialize(_gameId, _testMode, this);
        }
    }

 
    public void OnInitializationComplete()
    {
        Debug.Log("Unity Ads initialization complete.");
    }
 
    public void OnInitializationFailed(UnityAdsInitializationError error, string message)
    {
        Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
    }
}

三、添加广告

1.插页式广告

要使用 Advertisements API 展示全屏插页式广告,请初始化 SDK,然后使用 Load 函数将广告内容加载到 Ad Unit 和 Show 函数展示广告。

using UnityEngine;
using UnityEngine.Advertisements;
 
public class InterstitialAdExample : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] string _androidAdUnitId = "Interstitial_Android";
    [SerializeField] string _iOsAdUnitId = "Interstitial_iOS";
    string _adUnitId;
 
    void Awake()
    {
        // Get the Ad Unit ID for the current platform:
        _adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
            ? _iOsAdUnitId
            : _androidAdUnitId;
    }
 
    // Load content to the Ad Unit:
    public void LoadAd()
    {
        // IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
        Debug.Log("Loading Ad: " + _adUnitId);
        Advertisement.Load(_adUnitId, this);
    }
 
    // Show the loaded content in the Ad Unit:
    public void ShowAd()
    {
        // Note that if the ad content wasn't previously loaded, this method will fail
        Debug.Log("Showing Ad: " + _adUnitId);
        Advertisement.Show(_adUnitId, this);
    }
 
    // Implement Load Listener and Show Listener interface methods: 
    public void OnUnityAdsAdLoaded(string adUnitId)
    {
        // Optionally execute code if the Ad Unit successfully loads content.
    }
 
    public void OnUnityAdsFailedToLoad(string _adUnitId, UnityAdsLoadError error, string message)
    {
        Debug.Log($"Error loading Ad Unit: {_adUnitId} - {error.ToString()} - {message}");
        // Optionally execute code if the Ad Unit fails to load, such as attempting to try again.
    }
 
    public void OnUnityAdsShowFailure(string _adUnitId, UnityAdsShowError error, string message)
    {
        Debug.Log($"Error showing Ad Unit {_adUnitId}: {error.ToString()} - {message}");
        // Optionally execute code if the Ad Unit fails to show, such as loading another ad.
    }
 
    public void OnUnityAdsShowStart(string _adUnitId) { }
    public void OnUnityAdsShowClick(string _adUnitId) { }
    public void OnUnityAdsShowComplete(string _adUnitId, UnityAdsShowCompletionState showCompletionState) { }
}

2.激励广告

奖励观看广告的玩家可以提高用户参与度,从而带来更高的收入。例如,游戏可能会用游戏内货币、消耗品、额外生命或经验乘数奖励玩家。

要奖励完成视频广告的玩家,请实施一个回调方法,使用结果来检查用户是否完成了广告并应获得奖励。ShowResult
使用提示玩家选择观看广告的按钮是激励视频广告的常见实现方式。在以下步骤中使用示例代码创建激励广告按钮。只要广告内容可用,按下该按钮就会显示广告。

(1)创建按钮A绑定LoadAd方法
(2)创建按钮B绑定到脚本的_showAdButton变量
需要现请求广告内容,请求完毕后,在播放广告。

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;
 
public class RewardedAdsButton : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] Button _showAdButton;
    [SerializeField] string _androidAdUnitId = "Rewarded_Android";
    [SerializeField] string _iOSAdUnitId = "Rewarded_iOS";
    string _adUnitId = null; // This will remain null for unsupported platforms
 
    void Awake()
    {   
        // Get the Ad Unit ID for the current platform:
#if UNITY_IOS
        _adUnitId = _iOSAdUnitId;
#elif UNITY_ANDROID
        _adUnitId = _androidAdUnitId;
#endif

        // Disable the button until the ad is ready to show:
        _showAdButton.interactable = false;
    }
 
    // Call this public method when you want to get an ad ready to show.
    public void LoadAd()
    {
        // IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
        Debug.Log("Loading Ad: " + _adUnitId);
        Advertisement.Load(_adUnitId, this);
    }
 
    // If the ad successfully loads, add a listener to the button and enable it:
    public void OnUnityAdsAdLoaded(string adUnitId)
    {
        Debug.Log("Ad Loaded: " + adUnitId);
 
        if (adUnitId.Equals(_adUnitId))
        {
            // Configure the button to call the ShowAd() method when clicked:
            _showAdButton.onClick.AddListener(ShowAd);
            // Enable the button for users to click:
            _showAdButton.interactable = true;
        }
    }
 
    // Implement a method to execute when the user clicks the button:
    public void ShowAd()
    {
        // Disable the button:
        _showAdButton.interactable = false;
        // Then show the ad:
        Advertisement.Show(_adUnitId, this);
    }
 
    // Implement the Show Listener's OnUnityAdsShowComplete callback method to determine if the user gets a reward:
    public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
    {
        if (adUnitId.Equals(_adUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
        {
            Debug.Log("Unity Ads Rewarded Ad Completed");
            // Grant a reward.
        }
    }
 
    // Implement Load and Show Listener error callbacks:
    public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
    {
        Debug.Log($"Error loading Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Use the error details to determine whether to try to load another ad.
    }
 
    public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
    {
        Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Use the error details to determine whether to try to load another ad.
    }
 
    public void OnUnityAdsShowStart(string adUnitId) { }
    public void OnUnityAdsShowClick(string adUnitId) { }
 
    void OnDestroy()
    {
        // Clean up the button listeners:
        _showAdButton.onClick.RemoveAllListeners();
    }
}

3.横幅广告

在脚本头中,声明包含 Banner 类的命名空间。接下来,初始化 SDK,然后使用 Banner.Load 和 Banner.Show 方法加载并展示横幅广告。UnityEngine.Advertisements

以下示例脚本演示如何在场景中设置按钮以测试此功能。要在 Unity 编辑器中创建按钮,请在 UI > Button >选择 Game Object 。

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;
 
public class BannerAdExample : MonoBehaviour
{
    // For the purpose of this example, these buttons are for functionality testing:
    [SerializeField] Button _loadBannerButton;
    [SerializeField] Button _showBannerButton;
    [SerializeField] Button _hideBannerButton;
 
    [SerializeField] BannerPosition _bannerPosition = BannerPosition.BOTTOM_CENTER;
 
    [SerializeField] string _androidAdUnitId = "Banner_Android";
    [SerializeField] string _iOSAdUnitId = "Banner_iOS";
    string _adUnitId = null; // This will remain null for unsupported platforms.
 
    void Start()
    {
        // Get the Ad Unit ID for the current platform:
#if UNITY_IOS
        _adUnitId = _iOSAdUnitId;
#elif UNITY_ANDROID
        _adUnitId = _androidAdUnitId;
#endif

        // Disable the button until an ad is ready to show:
        _showBannerButton.interactable = false;
        _hideBannerButton.interactable = false;
 
        // Set the banner position:
        Advertisement.Banner.SetPosition(_bannerPosition);
 
        // Configure the Load Banner button to call the LoadBanner() method when clicked:
        _loadBannerButton.onClick.AddListener(LoadBanner);
        _loadBannerButton.interactable = true;
    }
 
    // Implement a method to call when the Load Banner button is clicked:
    public void LoadBanner()
    {
        // Set up options to notify the SDK of load events:
        BannerLoadOptions options = new BannerLoadOptions
        {
            loadCallback = OnBannerLoaded,
            errorCallback = OnBannerError
        };
 
        // Load the Ad Unit with banner content:
        Advertisement.Banner.Load(_adUnitId, options);
    }
 
    // Implement code to execute when the loadCallback event triggers:
    void OnBannerLoaded()
    {
        Debug.Log("Banner loaded");
 
        // Configure the Show Banner button to call the ShowBannerAd() method when clicked:
        _showBannerButton.onClick.AddListener(ShowBannerAd);
        // Configure the Hide Banner button to call the HideBannerAd() method when clicked:
        _hideBannerButton.onClick.AddListener(HideBannerAd);
 
        // Enable both buttons:
        _showBannerButton.interactable = true;
        _hideBannerButton.interactable = true;     
    }
 
    // Implement code to execute when the load errorCallback event triggers:
    void OnBannerError(string message)
    {
        Debug.Log($"Banner Error: {message}");
        // Optionally execute additional code, such as attempting to load another ad.
    }
 
    // Implement a method to call when the Show Banner button is clicked:
    void ShowBannerAd()
    {
        // Set up options to notify the SDK of show events:
        BannerOptions options = new BannerOptions
        {
            clickCallback = OnBannerClicked,
            hideCallback = OnBannerHidden,
            showCallback = OnBannerShown
        };
 
        // Show the loaded Banner Ad Unit:
        Advertisement.Banner.Show(_adUnitId, options);
    }
 
    // Implement a method to call when the Hide Banner button is clicked:
    void HideBannerAd()
    {
        // Hide the banner:
        Advertisement.Banner.Hide();
    }
 
    void OnBannerClicked() { }
    void OnBannerShown() { }
    void OnBannerHidden() { }
 
    void OnDestroy()
    {
        // Clean up the listeners:
        _loadBannerButton.onClick.RemoveAllListeners();
        _showBannerButton.onClick.RemoveAllListeners();
        _hideBannerButton.onClick.RemoveAllListeners();
    }
}

默认情况下,横幅广告固定在屏幕的底部中央,支持 320 x 50 或 728 x 90 像素分辨率。要指定横幅锚点,请使用 API。例如:Banner.SetPosition

Advertisement.Banner.SetPosition (BannerPosition.TOP_CENTER);

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

JavaEE 第17节 网络通信知识扫盲

文章目录 前言一、网络通信的概念二、局域网&广域网 局域网(LAN,Local Area Network) 广域网 三、IP地址与端口号 1、IP地址 2、端口号 四、网络协议 1、概念&作用 2、协议分层(重要) 前言 此篇博…

你是如何更精准地指引模型,激发其无尽的创造力?

随着大型语言模型日益凸显其重要性,发掘并充分利用它们的潜力,很大程度上依赖于我们如何巧妙构思和构造指令——即Prompt的精炼艺术。优化Prompt撰写技巧,将能够更好地引导大模型,为各类应用场景生成高质量的文本输出。分享出你的…

CTF杂项题:easy_nbt writeup

题目 题目如图,有一个附件:file.7z 解题思路 CTF的杂项题,对于刚接触的人员来说,很多时候是完全没有思路,解这类题,没有相关知识储备的时候,可以使用文件内容搜索工具搜索flag、ctf、key等关键…

【实现100个unity特效之25】Unity中实现二次元模型,基于光照的内置和URP管线卡通化渲染shader

最终效果 文章目录 最终效果默认效果简单粗暴,使用Unlit/Texture基于光照模型的卡通渲染UnityToonShader——仅支持内置渲染管线基于光照模型的二次元渲染UnityURPToonLitShaderExample——仅支持URP渲染管线 完结 默认效果 不然不做处理,我们的模型默认…

高并发eleme项目登录模块(thirty-three day)

一、配置一主二从mysql 1. mycat对mysql8不完全支持 2. mysql8主从问题不大get_pub_key1 3. gtids事务复制 4. 删除/etc/my.cnf 5. 同步data文件需要先停用mysql服务,删除data目录中的auto.cnf 6. gtid模式以及经典模式都需要锁表 flush tables with read lock; unlock …

怎么用电脑兼职赚钱,普通人可做的6个副业项目(非常详细)零基础入门到精通,收藏这篇就够了

现在的生活中,我们总是感觉所过的日子都很紧张,虽然我们尽可能地工作和努力,但是生活成本和社会压力仍然那么大。为了弥补自己的生活经验和财务困难,很多人开始寻找一种额外的收入来源。 其实这种额外的收入来源就被称之为&#…

google paly修改地区教程【2024自测可用】

【准备信息】 https://usfakename.com/ : 用来生成其他国家(比如美国)的地址 重要需要填写的内容: 卡号:4532 7875 1109 8437 City:Boulder State:Alabama postcode:35259 可以在美国邮政编码ZIP Code(转载) -…

学习yolo+Java+opencv简单案例(一)

目录 一、大概架构 二、编写pom.xml 1、yolo-study模块(root): 2、CameraDetection模块 三、编写yml配置文件 四、编写controller 五,可能会出现的问题 1、修改VM启动参数: 2、修改启动类 六、测试 七&…

gradio如何实现修改代码后自动重载运行

使用自动重载加速开发 前提条件:本指南要求你了解 Blocks。在阅读本指南之前,请确保你已经阅读了Blocks指南。 本指南涵盖自动重载、在Python IDE中的重载,以及在Jupyter Notebooks中使用Gradio。 为什么需要自动重载? 当你使…

C#归并排序算法

前言 归并排序是一种常见的排序算法,它采用分治法的思想,在排序过程中不断将待排序序列分割成更小的子序列,直到每个子序列中只剩下一个元素,然后将这些子序列两两合并并排序,最终得到一个有序的序列。 归并排序实现原…

蓝牙芯片 vs. 蓝牙模块:如何为蓝牙方案做出最佳选择?

不论您是设计全新的低功耗蓝牙产品,还是升级现有产品,开发者都面临的一个关键的选择:是采用蓝牙芯片还是蓝牙模块呢?作为蓝牙技术领域的资深专家,信驰达将从蓝牙芯片与蓝牙模块的各自优缺点进行分析,帮助您…

通过访存地址获取主存数据的过程

目录 1.根据访存地址在Cache中查找数据 2.如果在Cache中命中 3.如果没有命中 4.数据送CPU 5.做几道题: 主要厘清思路,中间细节需自行补充! 1.根据访存地址在Cache中查找数据 ① 访存地址的结构会根据Cache和主存之间的映射方式不同而改变。映射方式…

【MySql】 mysql的组从复制

mysql的组从复制 配置mastesr [rootmysql-node10 ~]# vim /etc/my.cnf [mysqld] datadir/data/mysql socket/data/mysql/mysql.sock symbolic-links0 log-binmysql-bin server-id1 [rootmysql-node10 ~]# /etc/init.d/mysqld restart #进入数据库配置用户权限 [rootmysql-nod…

方差稳定变换(Variance Stabilizing Transformation)介绍,专业生物学领域统计

介绍 方差稳定变换(Variance Stabilizing Transformation,VST)是一种统计方法,用于将一个具有异方差性的随机变量(即方差随着均值的变化而变化的变量)转换为方差相对稳定的变量。这种转换在数据分析和建模…

【网络】TCP协议详解(下)

上文介绍了TCP传输控制协议的报头,并且渗透了TCP保证可靠性的策略:如流量控制、按序到达、确认应答机制以及超时重传。本文继续讲解TCP剩下的协议,剩下俩个大话题,难度都比较麻烦。 本文将介绍TCP协议最常见的三次握手和四次挥手…

腾讯地图SDK Android版开发 7 覆盖物示例1

腾讯地图SDK Android版开发 7 覆盖物示例1 前言界面布局MapMarker类常量成员变量初始值Marker点击事件Marker拖拽事件创建覆盖物移除覆盖物设置属性 MapMarkerActivity类控件响应事件 运行效果图 前言 文本介绍Marker的常用属性、交互和碰撞示例。 示例功能如下: …

【计算机网络】认识端口号 认识传输层协议 认识网络字节序 认识socket套接字

👦个人主页:Weraphael ✍🏻作者简介:目前正在学习c和算法 ✈️专栏:Linux 🐋 希望大家多多支持,咱一起进步!😁 如果文章有啥瑕疵,希望大佬指点一二 如果文章对…

收银系统源码—千呼新零售【硬件篇】

连锁店收银系统源码—多商户平台入驻商城已上线-CSDN博客文章浏览阅读1k次。零售行业连锁店收银管理系统多商户入驻本地生活即时零售平台商城https://blog.csdn.net/V15850290240/article/details/141310629 详细介绍请查看上方文章↑↑↑ 详细介绍请查看上方文章↑↑↑ 详细…

[大模型]配置文件-Langchain-Chatchat-V0.3 (1)

文章目录 简述本地配置配置文件model_settings.yaml使用Ollama配置模型配置 使用Xinference配置模型配置修改默认使用的模型 对话基础对话知识库对话 简述 针对Langchain-Chatchat-V0.3版本,对配置文件与模型使用说明,本文建议使用Ollama配合Chatchat使…

用Python实现9大回归算法详解——09. 决策树回归算法

1. 决策树回归的基本概念 决策树回归(Decision Tree Regression)是一种树状结构的回归模型,通过对数据集进行递归分割,将数据分成更小的子集,并在每个子集上进行简单的线性回归。决策树的核心思想是通过选择特征及其阈…