Как подключить admob к unity
Добавление рекламы AdMob в Android-приложение, созданное на Unity3D + решение проблемы некликабельности
Доброго времени суток, уважаемые Хабровчане, я понимаю, что данный пост уже был, но написан он ужасно, не понятно, к тому же указанный в нём метод ещё и не работает.
Поэтому сегодня я предлагаю к рассмотрению детальный туториал по созданию рекламы в Android-приложении, созданном на движке Unity3D, рассчитанный для новичков.
Начнём.
Что нам понадобится:
1) Плагин для Unity3D, ссылка на GitHub, скачиваем под нашу версию Unity;
2) Аккаунт в сервисе AdMob;
3) Сам движок Unity3D;
Сервис Admob будет предоставлять рекламу в наше приложение, засчитывать показы, клики и фиксировать это всё на Вашем аккаунте.
После процедуры регистрации нам нужно монетизировать новое приложение, выбираем соответствующую опцию.
Монетизируем новое приложение, потом его можно будет привязать к игре на Google Play после процедуры модерации.
Настройка аналитики так же на вкус и цвет, в зависимости от надобности. Admob выдаёт результаты не в реальном времени а по прошествии некоторого времени (по моим наблюдениям двое суток), когда аналитика позволяет видеть всё в реальном времени, если Вам нужны результаты сразу.
Следующим шагом будет создание рекламный блоков. Вы можете создать один для всей игры, а можете штук 20 для всех сцен в игре, тут исключительно Ваш выбор, я делаю несколько игровых блоков на весь игровой процесс, так как в каждом случае вводить ID блока на каждую сцену — достаточно муторное занятие и отличий по эффекивности не имеет, разве что каждый блок прогружается в отдельности от других и это увеличивает количество показов рекламы.
Создаём баннер с частотой обновления 60 секунд, на самом деле можно указать любое значение, но важно, чтобы это значение так же было указано в плагине, скоро дойдём до этой части.
После создания баннера мы получаем идентификатор рекламного блока в формате: ca-app-pub-ххххххххххххххх/хххххххххх, этот идентификатор и является привязкой нашего рекламного блока в приложении с сервисом Admob. На этом манипуляции с Admob закончены.
В префабе находится 3 скрипта, каждый отвечает за свою роль:
1) Ad Mob Plugin — главный скрипт, который и выдаёт нашу рекламу.
2) Ad Mob Plugin Debug — дополнительный скрипт, который показывает кнопки, с помощью которых можно менять положение / вид / размер баннера в приложении.
3) Ad Mob Plugin Mockup — макет баннера. Используется для теста рекламного блока на сцене.
Последние два скрипта используются для тестирования, их нужно обязательно отключить перед билдом игры, иначе Вы получите игру с кнопками и макетом. Я не буду останавливаться на этих скриптах, так как самый главный для нас — это первый скрипт.
Отмечу несколько главных полей с этом скрипте:
Publisher ID — это и есть тот самый идентификатор рекламного блока, который мы получили в Admob (ca-app-pub-ххххххххххххххх/хххххххххх). Соответственно вводим его в это поле.
Is Testing — режим тестирования. Обязательно убираем галочку перед билдом.
Size — размер баннера. Выбираем нужный (можно посмотреть в тестовом режиме каждый размер).
Orientation — ориентация по вертикали или по горизонтали.
Horizontal position — позиция по горизонтали.
Vertical position — позиция по вертикали.
Refresh Interval — частота обновления рекламного блока, ставим то же значения, что указали в Admob (60 сек.).
Load on Start — включение загрузки рекламы сразу при старте приложения.
Дальше идут настройки Target — включение режима направленной (таргетированной) рекламы на определённую аудиторию.
Напомню основные моменты: Перед билдом отключаем Is Testing в Ad Mob Plugin, отключаем в префабе Ad Mob Plugin Debug и Ad Mob Plugin Mockup, вписываем наш Идентификатор рекламного блока в Publisher ID. В сцене с рекламой один префаб Admob Plugin.
Билдим наше приложение и обяательно проверяем на кликабельность. Если Ваша реклама показывается, кликается и переносит Вас по ссылкам, значит всё хорошо и в дальнейшем чтении этого поста вы не нуждаетесь. Но будьте осторожны! Если Вы будете кликать очень много раз, это означает, что на 1000 показов рекламы у вас 1000 кликов, т.е. эффективность рекламы = 100%, чего, конечно же, никогда не бывает и Ваш аккаунт Admob могут забанить за накрутку кликов.
Если же после билда и инсталла приложения реклама в нём показывается, но при клике по ней ничего не происходит, тогда есть небольшие проблемы и Вам со мной по пути.
Вся суть проблемы заключается в файле Android Manifest плагина.
Находим в Unity манифест (идёт с плагином при установке), открываем в редакторе и переставляем в нём одну строчку:
Сохраняем манифест, билдим приложение и проверяем на кликабельность.
В следующем посте опишу реализацию leaderboard для Android приложения на Unity3D.
Get Started
This guide is intended for publishers who want to monetize a Unity app.
Integrating the Google Mobile Ads Unity plugin into an app, which you will do here, is the first step toward displaying AdMob ads and earning revenue. Once the integration is complete, you can choose an ad format (such as native or rewarded video) to get detailed implementation steps.
Prerequisites
Download the Mobile Ads Unity plugin
The Google Mobile Ads Unity plugin enables Unity developers to easily serve Google Mobile Ads on Android and iOS apps without having to write Java or Objective-C code. The plugin provides a C# interface for requesting ads that is used by C# scripts in your Unity project.
Use the links below to download the Unity package for the plugin or to take a look at its code on GitHub.
For easier ads integration using the Unity Editor, try the new Ad Placements Beta.
Import the Mobile Ads Unity plugin
Open your project in the Unity editor. Select Assets > Import Package > Custom Package and find the GoogleMobileAdsPlugin.unitypackage file you downloaded.
Make sure all of the files are selected and click Import.
Include the Mobile Ads SDK
The Google Mobile Ads Unity plugin is distributed with the Unity Play Services Resolver library. This library is intended for use by any Unity plugin that requires access to Android specific libraries (e.g., AARs) or iOS CocoaPods. It provides Unity plugins the ability to declare dependencies, which are then automatically resolved and copied into your Unity project.
Follow the steps listed below to ensure your project includes the Mobile Ads SDK.
Android
In the Unity editor, select Assets > External Dependency Manager > Android Resolver > Resolve. The Unity External Dependency Manager library will copy the declared dependencies into the Assets/Plugins/Android directory of your Unity app.
No additional steps are required to include the Mobile Ads SDK into the Unity project.
Set your AdMob app ID
In the Unity editor, select Assets > Google Mobile Ads > Settings from the menu.
Enable AdMob by clicking Enabled checkbox under Google AdMob section. Then enter your Android and iOS AdMob app ID in each field.
If your app uses Ad Manager instead of AdMob, enable Google Ad Manager by clicking Enabled checkbox under Google Ad Manager section.
Initialize the Mobile Ads SDK
Before loading ads, have your app initialize the Mobile Ads SDK by calling MobileAds.Initialize() This needs to be done only once, ideally at app launch.
Here’s an example of how to call Initialize() within the Start() method of a script attached to a GameObject :
If you are using mediation, you may wish to wait until the callback occurs before loading ads, as this will ensure that all mediation adapters are initialized.
Select an ad format
The Mobile Ads SDK is now included in your Unity app when deploying to either the Android or iOS platform. You’re now ready to implement an ad. AdMob offers a number of different ad formats, so you can choose the one that best fits your user experience needs.
Banner
Banner ads are rectangular image or text ads that occupy a spot within an app’s layout. They stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time. If you’re new to mobile advertising, they’re a great place to start.
Interstitial
Interstitials are full-screen ads that cover the interface of an app until closed by the user. They’re best used at natural pauses in the flow of an app’s execution, such as in between levels of a game or just after completing a task.
Native
Native is a component-based ad format that gives you the freedom to customize the way assets such as headlines and calls to action are presented in their apps. By choosing fonts, colors, and other details for yourself, you can create natural, unobtrusive ad presentations that can add to a rich user experience.
Rewarded
Rewarded video ads are full-screen video ads that users have the option of watching in full in exchange for in-app rewards.
Request app tracking transparency authorization
To display the app tracking transparency (ATT) authorization request for accessing the IDFA, use Unity’s iOS 14 Advertising Support package.
Same app key
Prerequisites: Google Mobile Ads Unity Plugin 6.1.0 or higher
The Google Mobile Ads SDK introduces the same app key to help you deliver more relevant and personalized ads by using data collected from the app the user is using.
The same app key is enabled by default, but you can disable it with the following API:
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Integrating Unity Ads with Mediation
This guide is intended for publishers who want to use the Google Mobile Ads SDK to load and display ads from Unity Ads via mediation. It covers how to add Unity Ads to an ad unit’s mediation configuration, how to set up Ad Network Optimization (ANO), and how to integrate the Unity Ads SDK and adapter into an Android app.
Supported ad formats and features
The AdMob mediation adapter for Unity Ads has the following capabilities:
Formats | |
---|---|
Banner | |
Interstitial | |
Rewarded | |
Native | |
Features | |
Adaptive banner | |
Ad network optimization (ANO) |
Requirements
Step 1: Set up Unity ads
On the Unity Ads Dashboard, navigate to the Project tab and click the New Project button.
Fill out the form and click Add Project at the bottom of the page to add your project to Unity Dashboard.
Once your project is created, navigate to the Monetization > Placements tab of your project and take note of the Game ID.
To create a new placement, click the Add Placement button.
For additional instructions on creating an ad placement, select the tab corresponding to your preferred ad format.
Banner
Enter your desired Placement ID, select Banner as the ad format and click Create Placement.
Interstitial
Enter your desired Placement ID, select Interstitial Video as the ad format and click Create Placement.
Rewarded
Enter your desired Placement ID, select Rewarded Video as the ad format and click Create Placement.
In addition to the Game ID and Placement ID you will also need your Unity Ads API Key and Organization core ID for setting up your AdMob ad unit ID.
Navigate to the Ads Data Export > API Access tab of the Unity Ads Dashboard and take note of the Monetization Stats API Access Key.
Then, navigate to the Settings tab of the Unity Ads Dashboard and take note of the Organization core ID.
Step 2: Configure mediation settings for your AdMob ad unit
You need to add Unity Ads to the mediation configuration for your ad unit. First sign in to your AdMob account.
Next, navigate to the Mediation tab. If you have an existing mediation group you’d like to modify, click the name of that mediation group to edit it, and skip ahead to Add Unity Ads as an ad source.
To create a new mediation group, select Create Mediation Group.
Enter your ad format and platform, then click Continue.
Give your mediation group a name, and select locations to target. Next, set the mediation group status to Enabled. Then click Add Ad Units, which will open up the ad unit selection overlay.
Associate this mediation group with your existing AdMob ad unit. Then click Done.
You should now see the ad units card populated with the ad units you selected.
Add Unity Ads as an ad source
In the Ad Sources card, select Add Ad Network. Then select Unity Ads.
Enable the Optimize switch. Enter your API Key and Organization core ID obtained in the previous section to set up ANO for Unity Ads. Then enter an eCPM value for Unity Ads and click Continue.
Next, enter the Game ID and Placement ID obtained in the previous section. Then click Done.
Finally, click Save.
Note: Ad Network Optimization takes a few days to gather data to accurately calculate eCPM for a mediation network. In the meantime, the ANO status will be PENDING, so you must manually set an eCPM value for the network. Once the eCPM can be calculated, ANO will automatically start updating the eCPM on your behalf.
Using rewarded ads
In the settings for your rewarded ad unit, provide values for the reward amount and reward type. Then, to ensure you provide the same reward to the user no matter which ad network is served, check the Apply to all networks in Mediation groups box.
For more information on setting reward values for AdMob ad units, see Create an ad unit.
Step 3: Import the Unity Ads SDK and adapter
Android Studio integration (recommended)
Add the following gradle dependencies with the latest versions of the Unity Ads SDK and adapter in your app-level build.gradle file:
Manual integration
Download the latest Unity Ads SDK ( unity-ads.aar ) from their GitHub repository and add it to your project.
Step 4: Additional code required
No Additional code is required for Unity ads integration.
Step 5: Test your implementation
Test ads can be enabled from the Unity Ads dashboard in two ways.
If you want to enable test ads for all devices, navigate to the Settings > Project Settings tab of your project. Under the Test Mode section, edit the Client test mode not overridden section, check Override client test mode box, select Force test mode ON and click Save.
If you want to enable test ads only for specific devices, navigate to the Ads Data Export > Test Devices tab. Under the Test Devices section, click the Add New Device button and fill out the resulting form.
Optional steps
EU consent and GDPR
Under the Google EU User Consent Policy, you must ensure that certain disclosures are given to, and consents obtained from, users in the European Economic Area (EEA) regarding the use of device identifiers and personal data. This policy reflects the requirements of the EU ePrivacy Directive and the General Data Protection Regulation (GDPR). When seeking consent, you must identify each ad network in your mediation chain that may collect, receive, or use personal data and provide information about each network’s use. Google currently is unable to pass the user’s consent choice to such networks automatically.
Follow the instructions below to enable or disable personalized ads for Unity Ads.
Unity Ads provides a GDPR Compliance guide that describes both automatic and manual solutions for user consent.
The following sample code shows how to pass consent information to the Unity Ads SDK manually. Should you choose to pass consent information to the Unity Ads SDK manually, it is recommended that this code is called prior to requesting ads via the Google Mobile Ads SDK.
Error codes
If the adapter fails to receive an ad from Unity Ads, publishers can check the underlying error from the ad response using ResponseInfo.getAdapterResponse() under the following classes:
Here are the codes and accompanying messages thrown by the UnityAds adapter when an ad fails to load:
Error code | Reason |
---|---|
0-10 | UnityAds SDK returned an error. See code for more details. |
101 | UnityAds server parameters configured in the AdMob UI are missing/invalid. |
102 | UnityAds returned a placement with a NO_FILL state. |
103 | UnityAds returned a placement with a DISABLED state. |
104 | UnityAds tried to show an ad with a null context. |
105 | Context used to initialize, load and/or show ads from Unity Ads is not an Activity instance. |
106 | UnityAds tried to show an ad that’s not ready to be shown. |
107 | UnityAds is not supported on the device. |
108 | UnityAds can only load 1 ad per placement at a time. |
109 | UnityAds finished with an ERROR state. |
200-204 | UnityAds Banner specific error. See code for more details. |
Unity Ads Android Mediation Adapter Changelog
Version 3.7.5.0
Built and tested with:
Version 3.7.4.0
Built and tested with:
Version 3.7.2.0
Built and tested with:
Version 3.7.1.0
Built and tested with:
Version 3.6.2.0
Built and tested with:
Version 3.6.0.0
Built and tested with:
Version 3.5.1.1
Built and tested with:
Version 3.5.1.0
Built and tested with:
Version 3.5.0.0
Built and tested with:
Version 3.4.8.0
Built and tested with:
Version 3.4.6.1
Built and tested with:
Version 3.4.6.0
Built and tested with:
Version 3.4.2.3
Built and tested with:
Version 3.4.2.2
Built and tested with:
Version 3.4.2.1
Built and tested with:
Version 3.4.2.0
Built and tested with:
Version 3.4.0.0
Built and tested with:
Version 3.3.0.0
Built and tested with:
Version 3.2.0.1
Version 3.2.0.0
Version 3.1.0.0
Version 3.0.1.0
Version 3.0.0.2
Version 3.0.0.1
Version 3.0.0.0
Version 2.3.0.0
Version 2.2.1.1
Version 2.2.1.0
Version 2.2.0.0
Version 2.1.2.0
Version 2.1.1.0
Version 2.1.0.0
Version 2.0.8.0
Version 2.0.7.0
Version 2.0.6.0
Version 2.0.5.0
Version 2.0.4.0
Version 2.0.2.0
Version 1.0.0
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Русские Блоги
Admob Unity3d ad plugin введение, руководство по разработке и установке
Введение в плагин Admob Unity
Плагин Admob для Unity позволяет интегрировать рекламу admob в приложения Unity3D Game и u3d. Вы можете использовать его для приложений Unity iOS и Android с тем же кодом C # или js.
Это плагин Admob SDK для Unity3d. Этот плагин упрощает разработчикам js и c # добавление рекламы Google в игры Unity3d. Он поддерживает iOS и Android, а также поддерживает межстраничные объявления и баннеры admob.
Описание плагина Admob Unity
Этот репозиторий содержит исходный код подключаемого модуля Google Mobile Ads Unity. Плагин позволяет разработчикам Unity легко размещать мобильные объявления Google в приложениях для Android и iOS без написания кода Java или Objective-C. Подключаемый модуль предоставляет интерфейс C # для запроса рекламных объявлений, используемых сценариями C # в проекте Unity.
Возможности плагина Unity Admob
Платформы, поддерживаемые плагином:
Скачать плагин Admob Unity
Требуются AdmobPluginRes / GoogleMobileAds.framework и admob_unity_plugin.unitypackage. пожалуйста
С главной страницы проекта плагина Admob Unity3dhttps://github.com/unity-plugins/Unity-AdmobЗагрузите эти файлы,
Или загрузите все проекты плагинов AdMob для Unityhttps://github.com /unity-plugins/Unity-Admob/archive/master.zip
Установить Admob Unity
Вы можете установить его, скачав файл и поместив в папкуПлагинСкопируйте файлы прямо в проект Unity3d,
Wiki и документация плагина Unity
Быстрый старт
Отредактируйте AndroidManifest.xml и настройте идентификатор приложения Admob.
Admob требует эту конфигурацию с версии 17.0. Если она не настроена,Приложение выйдет из строя.Добавьте тег метаданных в приложение и установите значение admob appid
Отредактируйте Info.plist, добавьте appid
Настройте экспортированный проект Xcode, настройки сборки-> другие флаги компоновщика, добавьте flags-ObjC
1.Запустите плагин Admob Unity
Создайте скрипт AC #, перетащите скрипт на объект в сцене, добавьте следующий код в файл скрипта
Вы можете установить свойства admob следующим образом, вам нужно установить свойства, которые будут установлены
2. Добавьте баннер Admob в приложение Unity
Это минимальный код, необходимый для отображения баннеров admob.
Или вы можете создать другой баннер, указав название баннера
Класс AdPosition указывает, где разместить баннер. AdSize указывает баннер размера ведьмы, который будет отображаться
По умолчанию баннер виден. Чтобы скрыть баннер, звоните:
4. Как интегрировать межстраничную рекламу в приложения Unity 3D?
Это минимальный код для создания межстраничной рекламы.
В отличие от баннерной рекламы, межстраничные объявления должны отображаться четко. В соответствующей точке остановки приложения перед показом межстраничной рекламы убедитесь, что оно готово:
5. Настройте размер рекламного баннера Admob.
КромеAdSizeКонстанты наза пределами, Вы также можете создавать нестандартные размеры:
6. Как интегрировать видео вознаграждения Admob в приложение Unity3d?
Это минимальный код для создания admob-видео.
Видео, похожие на межстраничные, должны четко отображаться в соответствующей точке остановки в вашем приложении. Прежде чем показывать видео, проверьте, готово ли видео:
7. Отображение нативной расширенной рекламы Admob в приложении для iOS и Android.
Это минимальный код, необходимый для отображения баннеров admob. Это достигается с помощью Admob Native Ads Premium (Unified).
8. Рекламная кампания.
Эти двоеБаннерысМежстраничноеВы можете зарегистрироваться для участия в той же рекламной кампании. Здесь мы продемонстрируем настройку рекламного события для межстраничного объявления и покажем его после успешной загрузки:
Вам нужно только зарегистрироваться на те события, которые вам интересны.