levelplay-unity-integration
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLevelPlay Unity package/SDK Integration
LevelPlay Unity 包/SDK 集成
The C# scripts generated in this skill are MonoBehaviour files for the user to save to their project, not for inline execution.
Follow the integration workflow sequentially, one step at a time. Ask only the questions for the current step — do not gather information for future steps in advance. Wait for the user's response at each checkpoint before proceeding.
LevelPlay is Unity's ad mediation platform: it connects your game to multiple ad networks simultaneously and runs a unified auction across multiple ad networks and bidders to maximize competition for each impression. This guide walks you through the full integration: installing the SDK, configuring dependencies for Android and iOS, initializing LevelPlay in your project, and implementing rewarded, interstitial, and banner ads. If you already have part of this set up, you can skip ahead to the relevant step.
本技能生成的C#脚本是MonoBehaviour文件,供用户保存到自己的项目中,而非用于内联执行。
请按顺序遵循集成工作流,一步一步操作。仅询问当前步骤相关的问题——不要提前收集后续步骤所需的信息。在每个检查点等待用户回复后再继续。
LevelPlay是Unity的广告中介平台:它可同时将你的游戏连接到多个广告网络,并在多个广告网络和竞价方之间运行统一拍卖,以最大化每次展示的竞争度。本指南将引导你完成完整的集成流程:安装SDK、配置Android和iOS的依赖项、在项目中初始化LevelPlay,以及实现激励广告、插屏广告和横幅广告。如果你已完成部分设置,可以直接跳转到相关步骤。
Integration Workflow
集成工作流
1. Verify Unity Environment
1. 验证Unity环境
Check that the user is working in a Unity project by verifying Assets/ and ProjectSettings/ directories exist. If not in a Unity project, instruct the user to navigate to their Unity project directory. If those directories are not found but the user believes they are in the right place, ask: "It looks like you may not be at your project root — can you navigate to the top-level folder of your Unity project and confirm you can see Assets/ and ProjectSettings/ there?"
通过确认Assets/和ProjectSettings/目录是否存在,检查用户是否在Unity项目中工作。如果不在Unity项目中,指导用户导航到自己的Unity项目目录。如果未找到这些目录,但用户认为自己处于正确位置,请询问:"看起来你可能不在项目根目录——能否导航到Unity项目的顶层文件夹,并确认你能看到Assets/和ProjectSettings/目录?"
2. Understand Business Goals
2. 明确业务目标
Before implementing ad units, determine the user's optimization priorities to recommend the appropriate ad unit strategy. Ask:
"What's your primary optimization goal?"
- Revenue-focused: Maximize ad revenue and impression opportunities
- UX-focused: Prioritize gameplay flow and user satisfaction
- Balanced: Optimize for both revenue and UX
- Not sure yet: Default to Balanced and proceed. At Step 8, briefly note you're using Balanced since they were unsure, and invite them to indicate a different preference now that they've seen the format options.
Record this answer for later strategy recommendation in Step 8.
在实现广告单元之前,确定用户的优化优先级,以推荐合适的广告单元策略。询问:
"你的主要优化目标是什么?"
- 以收入为导向:最大化广告收入和展示机会
- 以用户体验为导向:优先保障游戏流程和用户满意度
- 平衡型:同时优化收入和用户体验
- 尚未确定:默认采用平衡型策略并继续推进。在步骤8中,简要说明由于用户尚未确定目标,因此使用平衡型策略,并邀请用户在了解格式选项后表明不同偏好。
记录该答案,以便在步骤8中推荐策略时使用。
3. Install LevelPlay SDK via UPM
3. 通过UPM安装LevelPlay SDK
If the SDK is already installed: Ask the user to verify 'Ads Mediation' appears under 'Packages: In Project' in the Package Manager. If it does, proceed directly to Step 4.
Guide through installing the LevelPlay Unity package using Unity Package Manager:
- Open Unity → Window > Package Manager
- Select Unity Registry dropdown or Services tab
- Search for "Ads Mediation" package
- Review package description to confirm it's the LevelPlay SDK
- Click Install button
- Wait for package to download and import
When you install the package, you may see a prompt to install Mobile Dependency Resolver — click Import if it appears. This is covered in more detail in the next step.
Verify the package appears under "Packages: In Project" in Package Manager after installation.
Network Manager: Access Ads Mediation > Network Manager at any time to install additional ad network adapters and check for SDK and adapter updates.
For iOS builds, note that SKAdNetwork configuration will be needed later (reference when ready for iOS builds).
references/ios-setup.md如果SDK已安装:请用户确认"Ads Mediation"出现在Package Manager的"Packages: In Project"下。如果是,直接进入步骤4。
指导用户通过Unity Package Manager安装LevelPlay Unity包:
- 打开Unity → Window > Package Manager
- 选择Unity Registry下拉菜单或Services标签页
- 搜索"Ads Mediation"包
- 查看包描述以确认它是LevelPlay SDK
- 点击Install按钮
- 等待包下载并导入
安装包时,你可能会看到安装Mobile Dependency Resolver的提示——如果出现,请点击Import。这一步将在下一步中详细说明。
安装完成后,确认包出现在Package Manager的"Packages: In Project"下。
Network Manager:随时访问Ads Mediation > Network Manager以安装额外的广告网络适配器,并检查SDK和适配器的更新。
对于iOS构建,请注意稍后需要配置SKAdNetwork(准备好进行iOS构建时参考)。
references/ios-setup.md4. Resolve Native Dependencies (Critical)
4. 解决原生依赖项(关键步骤)
Critical for Android/iOS builds: LevelPlay requires native dependency resolution. Without this, code compiles in Unity Editor but fails during platform builds with gradle (Android) or CocoaPods (iOS) errors.
Platform checkpoint — ask before proceeding: "Which platform(s) are you targeting — iOS, Android, or both?" Record this. It determines which dependency resolution steps apply here, whether ATT is required (Step 6.5), and which testing steps are relevant (Step 10).
LevelPlay requires native Android/iOS libraries that Unity's package manager alone doesn't handle. A dependency manager bridges this gap. If you've never added one to your project, don't worry; we'll walk you through it.
Check for existing dependency manager:
Ask: "Do you have a dependency manager like Mobile Dependency Resolver (MDR), Unity External Dependency Manager (UEDM), or External Dependency Manager for Unity (EDM4U) installed? Check your Assets folder for these tools."
If unsure: Check Assets folder in Unity for folders named 'Mobile Dependency Resolver', 'External Dependency Manager', or 'EDM4U'. If you see any folder with these names, answer 'Yes'. If not, answer 'No'.
If they HAVE a dependency manager:
For Android:
- With newer versions of Mobile Dependency Resolver (shipped with the Ads Mediation package): Dependencies auto-resolve on build (no manual action needed). If unsure, try building first — if it fails, manually resolve via the Android Resolver menu.
- With older MDR or other managers: Go to Assets > [Your Dependency Manager] > Android Resolver > Resolve
- Example paths:
- MDR:
Assets > Mobile Dependency Resolver > Android Resolver > Resolve - EDM4U:
Assets > External Dependency Manager > Android Resolver > Resolve
- MDR:
- Menu paths may vary depending on dependency manager version. Look for 'Android Resolver' under your dependency manager's menu.
For iOS:
- All dependency managers require manual CocoaPods installation:
- MDR:
Assets > Mobile Dependency Resolver > iOS Resolver > Install Cocoapods - EDM4U:
Assets > External Dependency Manager > iOS Resolver > Install Cocoapods - UEDM: Similar path under Unity External Dependency Manager
- MDR:
Ask: "Have you run the dependency resolution for your target platform(s)?"
If targeting both Android and iOS, complete dependency resolution for both platforms before proceeding.
If they DON'T have a dependency manager:
If the user didn't see the Mobile Dependency Resolver prompt during installation (see Step 3), restart Unity Editor — the prompt may appear after restart. If it still doesn't appear, they may already have a dependency manager installed.
When prompted:
- Click Import on the prompt to install Mobile Dependency Resolver
- After installation:
- Android: Dependencies will auto-resolve on build (newer MDR versions)
- iOS: Go to Assets > Mobile Dependency Resolver > iOS Resolver > Install Cocoapods
Alternative: Install another dependency manager like EDM4U if preferred (search for installation instructions in their documentation).
Note: Unity is transitioning to Unity External Dependency Manager (UEDM). If available in your Unity version, prefer UEDM over MDR.
Verification:
After resolution, verify:
- Android: Gradle dependencies in
Assets/Plugins/Android/ - iOS: Podfile references or CocoaPods installation confirmation in console
If dependency resolution fails: Check the Unity console for specific error messages and share them for troubleshooting — or see the Common Issues and Solutions section below for gradle and CocoaPods error guidance.
Android Custom Main Gradle Template (Older LevelPlay Versions):
For older LevelPlay Unity package versions, manually enable the Custom Main Gradle Template:
- Go to Edit > Project Settings > Player
- Select Android tab
- Expand Publishing Settings
- Under Build, check Custom Main Gradle Template
In newer LevelPlay Unity package versions (with newer Mobile Dependency Resolver), this is enabled automatically by default.
Android API 33+ Requirement:
If targeting Android API level 33 or higher, declare the AD_ID permission in AndroidManifest.xml:
xml
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>This permission is required for advertising ID access on Android 13+.
If you skip this step and target Android API 33+: advertising ID access will fail on Android 13+ devices.
对Android/iOS构建至关重要:LevelPlay需要解决原生依赖项。如果不执行此步骤,代码在Unity编辑器中可以编译,但在平台构建期间会出现gradle(Android)或CocoaPods(iOS)错误。
平台检查点——继续前询问:"你针对的是哪个平台?iOS、Android还是两者兼顾?"记录答案。这将决定此处适用的依赖项解决步骤、是否需要ATT(步骤6.5)以及相关的测试步骤(步骤10)。
LevelPlay需要原生Android/iOS库,而Unity的包管理器无法单独处理这些库。依赖项管理器可填补这一空白。如果你从未在项目中添加过依赖项管理器,不用担心——我们会引导你完成操作。
检查现有依赖项管理器:
询问:"你是否安装了Mobile Dependency Resolver(MDR)、Unity External Dependency Manager(UEDM)或External Dependency Manager for Unity(EDM4U)等依赖项管理器?请检查你的Assets文件夹中是否有这些工具。"
如果不确定:在Unity中检查Assets文件夹,查看是否有名为'Mobile Dependency Resolver'、'External Dependency Manager'或'EDM4U'的文件夹。如果看到任何这些名称的文件夹,请回答'是'。如果没有,请回答'否'。
如果已安装依赖项管理器:
针对Android:
- 对于较新版本的Mobile Dependency Resolver(随Ads Mediation包一起发布):依赖项会在构建时自动解决(无需手动操作)。如果不确定,先尝试构建——如果失败,通过Android Resolver菜单手动解决。
- 对于旧版MDR或其他管理器:转到Assets > [你的依赖项管理器] > Android Resolver > Resolve
- 示例路径:
- MDR:
Assets > Mobile Dependency Resolver > Android Resolver > Resolve - EDM4U:
Assets > External Dependency Manager > Android Resolver > Resolve
- MDR:
- 菜单路径可能因依赖项管理器版本而异。在依赖项管理器的菜单下查找'Android Resolver'。
针对iOS:
- 所有依赖项管理器都需要手动安装CocoaPods:
- MDR:
Assets > Mobile Dependency Resolver > iOS Resolver > Install Cocoapods - EDM4U:
Assets > External Dependency Manager > iOS Resolver > Install Cocoapods - UEDM:在Unity External Dependency Manager下的类似路径
- MDR:
询问:"你是否已针对目标平台执行了依赖项解决操作?"
如果同时针对Android和iOS,请在继续前完成两个平台的依赖项解决。
如果未安装依赖项管理器:
如果用户在安装过程中未看到Mobile Dependency Resolver提示(见步骤3),请重启Unity编辑器——重启后可能会出现提示。如果仍然未出现,用户可能已安装了依赖项管理器。
出现提示时:
- 点击Import以安装Mobile Dependency Resolver
- 安装完成后:
- Android:依赖项会在构建时自动解决(较新版本的MDR)
- iOS:转到Assets > Mobile Dependency Resolver > iOS Resolver > Install Cocoapods
替代方案:如果偏好其他依赖项管理器,可安装EDM4U等(在其文档中查找安装说明)。
注意:Unity正在过渡到Unity External Dependency Manager(UEDM)。如果你的Unity版本支持UEDM,优先使用UEDM而非MDR。
验证:
解决依赖项后,验证:
- Android:中的Gradle依赖项
Assets/Plugins/Android/ - iOS:控制台中的Podfile引用或CocoaPods安装确认信息
如果依赖项解决失败:检查Unity控制台中的具体错误信息并分享以进行故障排除——或查看下方的常见问题与解决方案部分,获取gradle和CocoaPods错误的指导。
Android自定义主Gradle模板(旧版LevelPlay):
对于旧版LevelPlay Unity包,需手动启用自定义主Gradle模板:
- 转到Edit > Project Settings > Player
- 选择Android标签页
- 展开Publishing Settings
- 在Build下,勾选Custom Main Gradle Template
在新版LevelPlay Unity包(搭配新版Mobile Dependency Resolver)中,此选项默认自动启用。
Android API 33+要求:
如果针对Android API级别33或更高版本,请在AndroidManifest.xml中声明AD_ID权限:
xml
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>此权限是Android 13+设备上访问广告ID所必需的。
如果跳过此步骤并针对Android API 33+:Android 13+设备上的广告ID访问将失败。
5. Get App Key and Ad Unit IDs
5. 获取应用密钥和广告单元ID
Before initializing LevelPlay, collect credentials from the LevelPlay dashboard.
Dashboard: https://platform.ironsrc.com/
New to LevelPlay? Set up your app and ad units first:
App Key: In the dashboard, go to Apps in the left sidenav → find your app → copy the alphanumeric string displayed under the app title.
Ad Unit IDs: Go to Ad units in the left sidenav → select your app → copy the ID for each format you plan to implement (Rewarded, Interstitial, Banner).
Note: You need your App Key now for initialization (Step 7). Ad Unit IDs are only needed at Step 9 — if you haven't decided which ad formats to implement yet, just copy your App Key for now and return here after Step 8.
Keep both accessible — you'll need them in the next steps.
在初始化LevelPlay之前,从LevelPlay控制台收集凭据。
首次使用LevelPlay? 先设置你的应用和广告单元:
应用密钥:在控制台中,转到左侧导航栏的Apps → 找到你的应用 → 复制应用标题下方显示的字母数字字符串。
广告单元ID:转到左侧导航栏的Ad units → 选择你的应用 → 复制计划实现的每种格式(激励广告、插屏广告、横幅广告)的ID。
注意:现在初始化(步骤7)需要应用密钥。广告单元ID仅在步骤9中需要——如果你尚未决定要实现哪些广告格式,只需先复制应用密钥,待步骤8完成后再返回此处。
请妥善保存这两项信息——后续步骤会用到。
6. Configure AdMob Keys (If Using AdMob Network)
6. 配置AdMob密钥(如果使用AdMob网络)
When to use: Only if using AdMob as a mediation network adapter in LevelPlay.
If using AdMob, configure platform-specific app keys in Unity Editor:
Access: Ads Mediation > Developer Settings > LevelPlay Mediation Settings
Configuration:
- Android App Key: AdMob Android app key
- iOS App Key: AdMob iOS app key
This configuration is required for AdMob to work as a mediation network in LevelPlay.
Troubleshooting: If you don't see the 'Ads Mediation' menu in Unity Editor, verify the Ads Mediation package is installed (Step 3) and restart Unity Editor.
适用场景:仅当在LevelPlay中使用AdMob作为中介网络适配器时。
如果使用AdMob,请在Unity编辑器中配置平台特定的应用密钥:
访问路径:Ads Mediation > Developer Settings > LevelPlay Mediation Settings
配置:
- Android App Key:AdMob Android应用密钥
- iOS App Key:AdMob iOS应用密钥
此配置是AdMob在LevelPlay中作为中介网络正常工作所必需的。
故障排除:如果在Unity编辑器中未看到'Ads Mediation'菜单,请确认已安装Ads Mediation包(步骤3)并重启Unity编辑器。
6.5. Privacy & Regulation Settings (If Required)
6.5. 隐私与监管设置(如需要)
Note: This skill provides technical integration guidance, including for LevelPlay's privacy APIs. It is not legal advice, and it does not determine which laws apply to your app — that depends on your users, your data practices, and your distribution. Consult your own legal counsel, and refer to Regulation Advanced Settings for Unity for the authoritative LevelPlay documentation.
Ask the user: "Do you need to configure privacy settings for GDPR, CCPA/CPRA (or certain state privacy consumer acts), or for child-directed apps?"
If YES to any:
Privacy settings must be configured BEFORE SDK initialization. See for complete implementation guide.
references/privacy-settings.mdQuick examples:
GDPR:
SDK 9.5.0+ — global consent boolean:
csharp
using Unity.Services.LevelPlay;
// true = user has granted consent, false = user has not consented
LevelPlayPrivacySettings.SetGDPRConsent(true);SDK 9.4.x — per-network consent dictionary (check your SDK version in Network Manager):
csharp
using Unity.Services.LevelPlay;
using System.Collections.Generic;
// Add an entry for each ad network you have installed
LevelPlayPrivacySettings.SetGDPRConsents(new Dictionary<string, bool> {
{ "UnityAds", true },
{ "IronSource", true }
// See references/privacy-settings.md for the full network key list
});If neither API compiles, your Unity package/SDK may be below 9.4.0 — upgrade via Ads Mediation > Network Manager.
CCPA (SDK 9.4.0+):
csharp
using Unity.Services.LevelPlay;
LevelPlayPrivacySettings.SetCCPA(true); // User opted out of data saleCOPPA (SDK 9.4.0+):
csharp
using Unity.Services.LevelPlay;
LevelPlayPrivacySettings.SetCOPPA(true); // Child-directed appThe CCPA and COPPA APIs above also require SDK 9.4.0+. If either fails to compile, upgrade your Unity package/SDK via Ads Mediation > Network Manager.
Call these BEFORE in Step 7.
LevelPlay.Init()For complete implementation with UI, consent management, and combined regulations, see .
references/privacy-settings.mdFor iOS builds — required regardless of privacy regulations above: Also implement App Tracking Transparency (ATT) before proceeding to Step 7. Apple requires ATT authorization before your app tracks users or accesses the device's advertising identifier on iOS 14.5+. Request ATT authorization before calling — this is both an Apple platform requirement and necessary for personalized ads (which also affects fill rate). See for the ATT implementation code.
LevelPlay.Init()references/ios-setup.mdIf NO privacy regulations and not targeting iOS: Skip this step and proceed to Step 7.
注意:本技能提供技术集成指导,包括LevelPlay的隐私API相关内容。但这并非法律建议,也不决定哪些法律适用于你的应用——这取决于你的用户、数据实践和分发渠道。请咨询自己的法律顾问,并参考Unity监管高级设置获取LevelPlay的权威文档。
询问用户:"你是否需要为GDPR、CCPA/CPRA(或某些州的消费者隐私法案)或面向儿童的应用配置隐私设置?"
如果任何一项为是:
必须在SDK初始化之前配置隐私设置。请查看获取完整的实施指南。
references/privacy-settings.md快速示例:
GDPR:
SDK 9.5.0+ — 全局同意布尔值:
csharp
using Unity.Services.LevelPlay;
// true = 用户已授予同意,false = 用户未授予同意
LevelPlayPrivacySettings.SetGDPRConsent(true);SDK 9.4.x — 按网络划分的同意字典(在Network Manager中检查你的SDK版本):
csharp
using Unity.Services.LevelPlay;
using System.Collections.Generic;
// 为每个已安装的广告网络添加条目
LevelPlayPrivacySettings.SetGDPRConsents(new Dictionary<string, bool> {
{ "UnityAds", true },
{ "IronSource", true }
// 完整的网络密钥列表请参考references/privacy-settings.md
});如果上述任一API无法编译,你的Unity包/SDK版本可能低于9.4.0——请通过Ads Mediation > Network Manager升级。
CCPA(SDK 9.4.0+):
csharp
using Unity.Services.LevelPlay;
LevelPlayPrivacySettings.SetCCPA(true); // 用户选择退出数据售卖COPPA(SDK 9.4.0+):
csharp
using Unity.Services.LevelPlay;
LevelPlayPrivacySettings.SetCOPPA(true); // 面向儿童的应用上述CCPA和COPPA API也需要SDK 9.4.0+。如果任一API编译失败,请通过Ads Mediation > Network Manager升级你的Unity包/SDK。
请在步骤7的之前调用这些方法。
LevelPlay.Init()如需包含UI、同意管理和多法规组合的完整实现,请查看。
references/privacy-settings.md针对iOS构建——无论上述隐私监管要求如何,均需执行:在继续步骤7之前,还需实现App Tracking Transparency(ATT)。Apple要求在iOS 14.5+设备上,应用跟踪用户或访问设备广告标识符之前,必须获得ATT授权。请在调用之前请求ATT授权——这既是Apple平台的要求,也是实现个性化广告(影响填充率)的必要条件。请查看获取ATT实现代码。
LevelPlay.Init()references/ios-setup.md如果无需隐私监管设置且不针对iOS:跳过此步骤,直接进入步骤7。
7. Initialize LevelPlay SDK
7. 初始化LevelPlay SDK
Installation checkpoint:
Before providing initialization code, confirm:
If the user confirmed they are not using AdMob, omit the Step 6 item from the confirmation below.
If following the sequential workflow and Steps 3 and 4 have already been confirmed in this conversation, skip those items — only ask about Step 5 and Step 6 (if AdMob).
"Please confirm these are working correctly:
- Step 3: Do you see the 'Ads Mediation' package in Unity Package Manager under 'Packages: In Project'?
- Step 4: Have you run dependency resolution for your target platform(s) without errors?
- Step 5: Do you have your App Key copied from the LevelPlay dashboard?
- Step 6 (only if using AdMob): Have you configured AdMob keys in Unity Editor settings?
Verify these are working before proceeding."
If they answer NO or are unsure:
- Missing Step 3: Code will show namespace errors → Direct to Step 3
CS0246 - Missing Step 4: Code compiles but Android/iOS builds will fail → Direct to Step 4
- Missing Step 5: They won't have credentials to initialize → Direct to Step 5
- Do not provide C# code until they confirm all steps are complete
If they answer YES:
- Optional — Analytics: ILRD Wiring. Ask this question verbatim — do not summarize or rephrase it: "Do you use an analytics or attribution platform (Firebase, AppsFlyer, Adjust, Singular, or custom backend) that needs ad revenue data? If yes, the init script will include a logging stub for Impression Level Revenue (ILRD) — 3 lines of code, no analytics platform setup required yet. (Yes / No / Not sure — defaults to yes)" Record the answer.
- Proceed with initialization code.
LevelPlay SDK must be initialized before loading or showing any ads. Initialization should happen early in the application lifecycle.
Ask how they want to handle initialization. Present all four options exactly as listed — do not condense or omit any:
- Create a new dedicated script for LevelPlay initialization
- Add to an existing initialization/manager script they already have
- Create a new LevelPlay script that your existing manager calls
- Just show me the initialization code — I'll decide how to integrate it
安装检查点:
在提供初始化代码之前,请确认:
如果用户确认未使用AdMob,请从以下确认项中省略步骤6的内容。
如果按顺序执行工作流,且本次对话中已确认步骤3和步骤4完成,请跳过这些项——仅询问步骤5和步骤6(如果使用AdMob)。
"请确认以下内容均正常工作:
- 步骤3:你是否在Unity Package Manager的'Packages: In Project'下看到'Ads Mediation'包?
- 步骤4:你是否已针对目标平台执行依赖项解决且无错误?
- 步骤5:你是否已从LevelPlay控制台复制应用密钥?
- 步骤6(仅当使用AdMob时):你是否已在Unity编辑器设置中配置AdMob密钥?
请在继续前验证这些内容。"
如果用户回答否或不确定:
- 未完成步骤3:代码会显示命名空间错误 → 引导至步骤3
CS0246 - 未完成步骤4:代码可编译,但Android/iOS构建会失败 → 引导至步骤4
- 未完成步骤5:没有初始化所需的凭据 → 引导至步骤5
- 在用户确认所有步骤完成之前,不要提供C#代码
如果用户回答是:
- 可选——分析:ILRD配置:请一字不差地询问以下问题,不要总结或改写:"你是否使用需要广告收入数据的分析或归因平台(Firebase、AppsFlyer、Adjust、Singular或自定义后端)?如果是,初始化脚本将包含展示级收入(ILRD)的日志存根——仅3行代码,暂时无需设置分析平台。(是/否/不确定——默认是)"记录答案。
- 继续提供初始化代码。
必须在加载或展示任何广告之前初始化LevelPlay SDK。初始化应在应用生命周期的早期进行。
询问用户希望如何处理初始化。请准确列出以下四个选项,不要压缩或省略任何一项:
- 创建一个新的专用脚本用于LevelPlay初始化
- 添加到现有的初始化/管理器脚本中
- 创建一个新的LevelPlay脚本,由现有管理器调用
- 直接展示初始化代码——我会决定如何集成
Option 1: Creating a New Script
选项1:创建新脚本
If creating a new script (e.g., ), use this complete class:
LevelPlayInitializer.cscsharp
using UnityEngine;
using Unity.Services.LevelPlay;
public class LevelPlayInitializer : MonoBehaviour
{
[SerializeField] private string appKey;
void Awake()
{
// Persist across scene loads so ads stay initialized
DontDestroyOnLoad(gameObject);
}
void Start()
{
// Register initialization callbacks
LevelPlay.OnInitSuccess += OnInitSuccess;
LevelPlay.OnInitFailed += OnInitFailed;
// Initialize the SDK with your App Key
LevelPlay.Init(appKey);
}
private void OnInitSuccess(LevelPlayConfiguration config)
{
Debug.Log("LevelPlay SDK initialized successfully");
// SDK is now ready to load ads
}
private void OnInitFailed(LevelPlayInitError error)
{
Debug.LogError($"LevelPlay initialization failed: {error.ErrorMessage}");
}
void OnDestroy()
{
LevelPlay.OnInitSuccess -= OnInitSuccess;
LevelPlay.OnInitFailed -= OnInitFailed;
}
}File location: Save as (or if you have an Ads subfolder)
Assets/Scripts/LevelPlayInitializer.csAssets/Scripts/Ads/LevelPlayInitializer.csAfter creating:
- Attach script to a GameObject in your first scene
- In Unity Inspector, find the "App Key" field
- Paste your App Key from Step 5 into that field
If the user answered Yes or Not Sure to ILRD in Step 7, also subscribe before Init. Add these lines inside (before ):
Start()LevelPlay.Init(appKey)csharp
// MUST be registered BEFORE LevelPlay.Init() to avoid losing early impressions.
// Callback fires on a BACKGROUND thread — see references/ilrd-api.md for
// thread-safe forwarding patterns and a Firebase example.
LevelPlay.OnImpressionDataReady += OnImpressionDataReady;Add this stub method to the class:
csharp
private void OnImpressionDataReady(LevelPlayImpressionData impressionData)
{
// See references/ilrd-api.md for full implementation.
// For now, just log so you can verify it fires:
Debug.Log($"ILRD: {impressionData.AdNetwork} / {impressionData.AdFormat} / ${impressionData.Revenue}");
}And unsubscribe in :
OnDestroy()csharp
LevelPlay.OnImpressionDataReady -= OnImpressionDataReady;Next: Once you confirm the log fires after your first ad impression, read to wire it up to your actual analytics platform. Note: ILRD callbacks do not fire with mock ads in the Unity Editor — you'll need a device build to verify this log fires (see Step 10).
references/ilrd-api.md如果创建新脚本(例如),请使用以下完整类:
LevelPlayInitializer.cscsharp
using UnityEngine;
using Unity.Services.LevelPlay;
public class LevelPlayInitializer : MonoBehaviour
{
[SerializeField] private string appKey;
void Awake()
{
// Persist across scene loads so ads stay initialized
DontDestroyOnLoad(gameObject);
}
void Start()
{
// Register initialization callbacks
LevelPlay.OnInitSuccess += OnInitSuccess;
LevelPlay.OnInitFailed += OnInitFailed;
// Initialize the SDK with your App Key
LevelPlay.Init(appKey);
}
private void OnInitSuccess(LevelPlayConfiguration config)
{
Debug.Log("LevelPlay SDK initialized successfully");
// SDK is now ready to load ads
}
private void OnInitFailed(LevelPlayInitError error)
{
Debug.LogError($"LevelPlay initialization failed: {error.ErrorMessage}");
}
void OnDestroy()
{
LevelPlay.OnInitSuccess -= OnInitSuccess;
LevelPlay.OnInitFailed -= OnInitFailed;
}
}文件位置:保存为(如果有Ads子文件夹,可保存为)
Assets/Scripts/LevelPlayInitializer.csAssets/Scripts/Ads/LevelPlayInitializer.cs创建后:
- 将脚本附加到第一个场景中的GameObject上
- 在Unity Inspector中找到"App Key"字段
- 将步骤5中的应用密钥粘贴到该字段中
如果用户在步骤7中回答是或不确定ILRD,请在Init之前订阅。在中添加以下代码(在之前):
Start()LevelPlay.Init(appKey)csharp
// MUST be registered BEFORE LevelPlay.Init() to avoid losing early impressions.
// Callback fires on a BACKGROUND thread — see references/ilrd-api.md for
// thread-safe forwarding patterns and a Firebase example.
LevelPlay.OnImpressionDataReady += OnImpressionDataReady;向类中添加以下存根方法:
csharp
private void OnImpressionDataReady(LevelPlayImpressionData impressionData)
{
// See references/ilrd-api.md for full implementation.
// For now, just log so you can verify it fires:
Debug.Log($"ILRD: {impressionData.AdNetwork} / {impressionData.AdFormat} / ${impressionData.Revenue}");
}并在中取消订阅:
OnDestroy()csharp
LevelPlay.OnImpressionDataReady -= OnImpressionDataReady;下一步:确认首次广告展示后日志触发后,请查看以将数据连接到实际的分析平台。注意:ILRD回调不会在Unity编辑器中的模拟广告中触发——你需要设备构建来验证此日志是否触发(见步骤10)。
references/ilrd-api.mdOption 2: Adding to Existing Script
选项2:添加到现有脚本
If adding to an existing script (e.g., ):
GameManager.cs1. Add namespace at top of file:
csharp
using Unity.Services.LevelPlay;2. In existing Start() or Awake() method, add initialization:
csharp
void Start()
{
// Register initialization callbacks
LevelPlay.OnInitSuccess += OnInitSuccess;
LevelPlay.OnInitFailed += OnInitFailed;
// Initialize the SDK - REPLACE with your actual App Key from Step 5
LevelPlay.Init("YOUR_APP_KEY_HERE");
// ... your other existing Start() code
}3. Add callback methods to class:
csharp
private void OnInitSuccess(LevelPlayConfiguration config)
{
Debug.Log("LevelPlay SDK initialized successfully");
// SDK is ready - you can now create ad objects
}
private void OnInitFailed(LevelPlayInitError error)
{
Debug.LogError($"LevelPlay initialization failed: {error.ErrorMessage}");
}4. In existing OnDestroy() (or create if it doesn't exist), add:
csharp
void OnDestroy()
{
// Unregister callbacks
LevelPlay.OnInitSuccess -= OnInitSuccess;
LevelPlay.OnInitFailed -= OnInitFailed;
}If the user answered Yes or Not Sure to ILRD in Step 7, add the same ILRD subscription code shown in Option 1 above: subscribe before , add the stub handler method, and unsubscribe in .
LevelPlay.Init(...)OnDestroy()Replace with your actual App Key from Step 5 (the alphanumeric string copied from the LevelPlay dashboard).
"YOUR_APP_KEY_HERE"Note: If your existing script doesn't already persist across scenes, add to its method to prevent re-initialization when loading new scenes.
DontDestroyOnLoad(gameObject);Awake()Before testing, double-check that you've replaced the placeholder with your actual App Key. The App Key should be an alphanumeric string, NOT 'YOUR_APP_KEY_HERE'.
如果添加到现有脚本(例如):
GameManager.cs1. 在文件顶部添加命名空间:
csharp
using Unity.Services.LevelPlay;2. 在现有的Start()或Awake()方法中添加初始化代码:
csharp
void Start()
{
// Register initialization callbacks
LevelPlay.OnInitSuccess += OnInitSuccess;
LevelPlay.OnInitFailed += OnInitFailed;
// Initialize the SDK - REPLACE with your actual App Key from Step 5
LevelPlay.Init("YOUR_APP_KEY_HERE");
// ... your other existing Start() code
}3. 向类中添加回调方法:
csharp
private void OnInitSuccess(LevelPlayConfiguration config)
{
Debug.Log("LevelPlay SDK initialized successfully");
// SDK is ready - you can now create ad objects
}
private void OnInitFailed(LevelPlayInitError error)
{
Debug.LogError($"LevelPlay initialization failed: {error.ErrorMessage}");
}4. 在现有的OnDestroy()中(如果不存在则创建)添加:
csharp
void OnDestroy()
{
// Unregister callbacks
LevelPlay.OnInitSuccess -= OnInitSuccess;
LevelPlay.OnInitFailed -= OnInitFailed;
}如果用户在步骤7中回答是或不确定ILRD,请添加与选项1中相同的ILRD订阅代码:在之前订阅,添加存根处理方法,并在中取消订阅。
LevelPlay.Init(...)OnDestroy()将替换为步骤5中的实际应用密钥(从LevelPlay控制台复制的字母数字字符串)。
"YOUR_APP_KEY_HERE"注意:如果现有脚本未跨场景持久化,请在其方法中添加,以避免加载新场景时重新初始化。
Awake()DontDestroyOnLoad(gameObject);测试前,请仔细检查是否已将占位符替换为实际应用密钥。应用密钥应为字母数字字符串,而非'YOUR_APP_KEY_HERE'。
Option 3: Separate Script Called by Manager
选项3:由管理器调用的独立脚本
If you want to keep ads code in its own script but have your existing manager control initialization:
1. Create using the complete class code from Option 1
LevelPlayInitializer.cs2. In existing manager script (e.g., ), add:
GameManager.cscsharp
using UnityEngine;
public class GameManager : MonoBehaviour
{
void Awake()
{
// Add LevelPlay initialization as a component
gameObject.AddComponent<LevelPlayInitializer>();
// ... your other initialization code
}
}This keeps ad code isolated in while controls when it initializes.
LevelPlayInitializer.csGameManagerNote: calls , which will mark this entire GameObject — including your GameManager and any other components on it — as persistent across scenes. Ensure this is compatible with your scene management strategy.
LevelPlayInitializer.Awake()DontDestroyOnLoad(gameObject)If the user answered Yes or Not Sure to ILRD in Step 7, add the ILRD subscription to as shown in Option 1 above. No changes needed in .
LevelPlayInitializer.csGameManagerBefore testing, ensure you've entered your actual App Key in the Unity Inspector's App Key field on the LevelPlayInitializer component (see Option 1's After Creating steps above).
如果你希望将广告代码保留在单独的脚本中,但由现有管理器控制初始化:
1. 使用选项1中的完整类代码创建
LevelPlayInitializer.cs2. 在现有管理器脚本(例如)中添加:
GameManager.cscsharp
using UnityEngine;
public class GameManager : MonoBehaviour
{
void Awake()
{
// Add LevelPlay initialization as a component
gameObject.AddComponent<LevelPlayInitializer>();
// ... your other initialization code
}
}这样可将广告代码隔离在中,同时由控制初始化时机。
LevelPlayInitializer.csGameManager注意:调用,这会将整个GameObject(包括你的GameManager和其上的任何其他组件)标记为跨场景持久化。请确保这与你的场景管理策略兼容。
LevelPlayInitializer.Awake()DontDestroyOnLoad(gameObject)如果用户在步骤7中回答是或不确定ILRD,请按选项1中的方式向添加ILRD订阅。无需修改。
LevelPlayInitializer.csGameManager测试前,请确保已在Unity Inspector的LevelPlayInitializer组件的App Key字段中输入实际应用密钥(见选项1中的创建后步骤)。
Option 4: Just Show Me the Code
选项4:直接展示代码
Provide the complete initialization code from Option 1 as a standalone snippet, without instructions for attaching to a GameObject or setting up the Inspector. Include a note: "This is the full initialization class — save it as , attach it to a persistent GameObject in your first scene, and set the App Key field in the Inspector."
LevelPlayInitializer.csKey points:
- Always register and
OnInitSuccesscallbacks before callingOnInitFailedInit() - Call initialization early in app lifecycle (in or
Awake()of first scene)Start() - Only initialize once. If initialization script is in first scene and you have multiple scenes, add in
DontDestroyOnLoad(gameObject);to prevent re-initialization when loading new scenesAwake() - Wait for before creating ad objects
OnInitSuccess
If initialization fails repeatedly, see the Common Issues section for troubleshooting. Common causes include incorrect App Key, no internet connection, or missing package dependencies.
For more advanced initialization options (user ID, consent management, etc.), see .
references/initialization-api.md提供选项1中的完整初始化代码作为独立片段,不包含附加到GameObject或设置Inspector的说明。添加注释:"这是完整的初始化类——将其保存为,附加到第一个场景中的持久化GameObject上,并在Inspector中设置App Key字段。"
LevelPlayInitializer.cs关键点:
- 始终在调用之前注册
Init()和OnInitSuccess回调OnInitFailed - 在应用生命周期的早期(第一个场景的或
Awake()中)调用初始化Start() - 仅初始化一次。如果初始化脚本在第一个场景中,且你有多个场景,请在中添加
Awake()以避免加载新场景时重新初始化DontDestroyOnLoad(gameObject); - 等待后再创建广告对象
OnInitSuccess
如果初始化反复失败,请查看常见问题部分进行故障排除。常见原因包括应用密钥错误、无网络连接或缺少包依赖项。
如需更高级的初始化选项(用户ID、同意管理等),请查看。
references/initialization-api.md8. Recommend Ad Unit Strategy
8. 推荐广告单元策略
Based on the optimization goal identified in Step 2, recommend an ad unit strategy.
Recall the user's optimization goal from Step 2. If the conversation has been long or the answer is unclear, confirm: "Earlier you mentioned your optimization goal. To confirm, are you primarily focused on revenue, user experience, or a balance of both?"
Map the answer to the appropriate strategy:
- User focused on maximizing revenue, impressions, or monetization → Use Revenue-Focused Strategy
- User focused on user experience, retention, or avoiding annoyance → Use UX-Focused Strategy
- User wants to balance both or mentioned both revenue and UX → Use Balanced Strategy
- User answered "Not sure yet" in Step 2 → Use Balanced Strategy. After presenting the recommendation, add: "Since you weren't sure of your goal earlier, I've gone with the Balanced approach — if you'd prefer to lean more toward revenue or user experience now that you've seen the options, just say so."
- If unclear, ask: "Would you prioritize revenue, user experience, or a balance of both?"
根据步骤2中确定的优化目标,推荐广告单元策略。
回顾步骤2中用户的优化目标。如果对话较长或答案不明确,请确认:"之前你提到了优化目标。为确认,你主要关注的是收入、用户体验还是两者兼顾?"
将答案映射到相应策略:
- 用户专注于最大化收入、展示量或变现 → 使用以收入为导向的策略
- 用户专注于用户体验、留存率或避免打扰用户 → 使用以用户体验为导向的策略
- 用户希望兼顾两者或提到收入和用户体验 → 使用平衡型策略
- 用户在步骤2中回答**"尚未确定"** → 使用平衡型策略。在展示推荐后添加:"由于你之前尚未确定目标,我采用了平衡型方法——如果你在了解选项后更倾向于收入或用户体验,请告知。"
- 如果答案不明确,请询问:"你更优先考虑收入、用户体验还是两者兼顾?"
Revenue-Focused Strategy
以收入为导向的策略
Goal: Maximize ad revenue and impression opportunities
Recommended ad units:
-
Rewarded ads: Primary monetization driver
- Implement in multiple high-value moments
- Use for premium rewards, extra lives, bonus content
- Load ads proactively to ensure availability
-
Interstitial ads: Secondary revenue source
- Show at natural transition points (level complete, game over)
- Frequency cap: Every 3-5 minutes of gameplay (see )
references/interstitial-api.md
-
Banner ads: Persistent revenue during gameplay
- Show during core gameplay loops
- Use smart positioning to avoid UI conflicts
Revenue lever: bid floor (optional)
Once ads are live, bid floors let you set a minimum bid price per ad unit — raising your average eCPM at the cost of lower fill rate. You'll be prompted in Step 9 to configure this or skip and add it later.
Implementation priority: Rewarded → Interstitial → Banner
The next step will ask you to choose which ad formats to implement from this priority list.
目标:最大化广告收入和展示机会
推荐广告单元:
-
激励广告:主要变现驱动因素
- 在多个高价值时刻实现
- 用于高级奖励、额外生命、附加内容
- 主动加载广告以确保可用
-
插屏广告:次要收入来源
- 在自然过渡点展示(关卡完成、游戏结束)
- 频率上限:每3-5分钟游戏时间(见)
references/interstitial-api.md
-
横幅广告:游戏过程中的持续收入
- 在核心游戏循环中展示
- 使用智能定位避免与UI冲突
收入杠杆:竞价底价(可选)
广告上线后,竞价底价可让你为每个广告单元设置最低竞价价格——提高平均eCPM,但可能降低填充率。步骤9中会提示你配置此项或跳过,稍后再添加。
实现优先级:激励广告 → 插屏广告 → 横幅广告
下一步将询问你从此优先级列表中选择要实现的广告格式。
UX-Focused Strategy
以用户体验为导向的策略
Goal: Maintain excellent user experience while monetizing thoughtfully
Recommended ad units:
-
Rewarded ads: Primary and often only ad format
- User-initiated only (explicit opt-in)
- High-value rewards that feel generous
- No forced ads, ever
-
Interstitial ads: Optional, sparingly used
- Only at major session boundaries (e.g., exiting to main menu)
- Never interrupt active gameplay
-
Banner ads: Generally avoided or minimized
- If used, only during menu screens, not gameplay
- Small, non-intrusive sizes
Implementation priority: Rewarded only, or Rewarded → (optional) Interstitial
The next step will ask you to choose which ad formats to implement from this priority list.
目标:在谨慎变现的同时保持出色的用户体验
推荐广告单元:
-
激励广告:主要且通常是唯一的广告格式
- 仅由用户主动触发(明确选择加入)
- 提供高价值奖励,让用户感觉实惠
- 绝不强制展示广告
-
插屏广告:可选,谨慎使用
- 仅在主要会话边界展示(例如返回主菜单时)
- 绝不打断活跃的游戏玩法
-
横幅广告:通常避免或尽量减少使用
- 如果使用,仅在菜单界面展示,而非游戏过程中
- 使用小尺寸、非侵入式的样式
实现优先级:仅激励广告,或激励广告 →(可选)插屏广告
下一步将询问你从此优先级列表中选择要实现的广告格式。
Balanced Strategy
平衡型策略
Goal: Optimize both revenue and user satisfaction
Recommended ad units:
-
Rewarded ads: Core monetization
- 2-3 strategic placements in high-engagement moments
- Rewards feel valuable but not exploitative
-
Interstitial ads: Moderate usage
- At natural breakpoints (level transitions, session ends)
- Frequency cap: Every 5-7 minutes (see )
references/interstitial-api.md
-
Banner ads: Selective placement
- Show in menus or low-attention moments
- Hide during intense gameplay
Implementation priority: Rewarded → Interstitial → Banner (selective)
The next step will ask you to choose which ad formats to implement from this priority list. If the user wants to implement in a different order than recommended, accommodate that preference.
目标:同时优化收入和用户满意度
推荐广告单元:
-
激励广告:核心变现方式
- 在高参与度时刻设置2-3个战略性展示位置
- 奖励有价值但不过度
-
插屏广告:适度使用
- 在自然断点展示(关卡过渡、会话结束)
- 频率上限:每5-7分钟(见)
references/interstitial-api.md
-
横幅广告:选择性展示
- 在菜单或低注意力时刻展示
- 在激烈游戏过程中隐藏
实现优先级:激励广告 → 插屏广告 → 横幅广告(选择性)
下一步将询问你从此优先级列表中选择要实现的广告格式。如果用户希望以不同于推荐的顺序实现,请满足其偏好。
9. Implement Ad Units
9. 实现广告单元
Important: Read Best Practices First
Before implementing ad code, read the Best Practices section below (after Step 10). It contains essential patterns for loading strategy, error handling, memory management, and placement strategy. These patterns should be incorporated into all ad implementations.
Implementation checkpoint:
Before implementing ad units, confirm:
"Before providing ad implementation code, please confirm:
- Did you complete SDK initialization in Step 7?
- Did you receive the 'LevelPlay SDK initialized successfully' log message in your Unity console?
Verify initialization is working before proceeding with ad units."
If they answer NO or are unsure:
- Direct back to Step 7 to complete initialization first
- Do not provide ad implementation code until initialization is confirmed working
If they answer YES, proceed with ad implementation.
Ad format checkpoint — ask before generating any code: "Which ad formats do you want to implement? Rewarded, Interstitial, Banner, or a combination?" Only implement the formats the user selects. They can add more formats later using the 'Adding More Ad Formats Later' section.
Based on the chosen strategy, implement the appropriate ad formats.
Implementation flexibility: Implement formats one at a time or all at once. Choose which formats you want to implement now, and you can always add more formats later (see 'Adding More Ad Formats Later' section below).
First, ask the user how they want to organize the ad code. Do not generate any code until they have answered:
"How would you like to structure your ad implementation?"
-
Separate manager scripts for each ad format - Create individual scripts like,
RewardedAdManager.cs,InterstitialAdManager.cs(good for larger projects, clear separation of concerns)BannerAdManager.cs -
One unified AdManager script - Create a singlethat handles all ad formats (simpler, everything in one place)
AdManager.cs -
Just show me the code snippets - Provide implementation code without wrapping it in specific files, so you can integrate it however you prefer
-
I already have ad manager code - Review and help fix/update existing implementation
Based on their answer, adapt your response accordingly.
Then present the optional bid floor feature (skip for Option 4 — review existing code instead):
Present bid floor ranges only for the formats the user is implementing in this session. Reference starting ranges: Rewarded: $0.50–$2.00 | Interstitial: $0.20–$1.00 | Banner: $0.05–$0.20. Include only the ranges for formats being implemented.
"Optional — Advanced: Bid Floors
Most publishers skip this initially and add it once they have real dashboard data. You can safely skip now and return to it later.
If you'd like to set bid floors now: a bid floor sets a minimum bid price (USD) per ad unit — it raises your average eCPM at the cost of lower fill rate. Starting ranges:
[ranges for formats being implemented]
Reply with values per format, or just say 'skip' — you can add them any time."
Record the answer per format. Wire into the ad construction for any format where a value was provided. Formats marked 'skip' use the basic constructor.
Config.Builder().SetBidFloor(...)If they choose Option 4 (existing code):
- Ask: "Please share your existing ad manager code for review"
- Wait for them to provide the code
- Analyze the existing implementation:
- Check if they're using current LevelPlay Ad Unit API (LevelPlayRewardedAd, LevelPlayInterstitialAd, LevelPlayBannerAd)
- Identify if they're using deprecated IronSource.Agent APIs
- Check for proper callback registration/unsubscription
- Look for missing error handling or memory leaks
- Provide specific guidance:
- If using deprecated APIs: "You're using the old IronSource.Agent API. Here's how to migrate to the new LevelPlay Ad Unit API:"
- If using current APIs with issues: "Your implementation looks good but I noticed [specific issues]. Here's how to fix them:"
- If implementation is correct: "Your implementation looks solid. Which additional ad formats would you like to add?"
- Offer to either:
- Provide fixes as code snippets to integrate into existing files
- Suggest refactoring if the code has structural issues
- When adding new formats after reviewing existing code, present the bid floor prompt scoped to those new formats only, confirm whether to match their existing code organization pattern or use a new one, then follow the same implementation guidelines as Options 1–3 above.
For each ad format, follow the implementation guidelines in detailed references:
- Rewarded ads: See
references/rewarded-api.md - Interstitial ads: See
references/interstitial-api.md - Banner ads: See
references/banner-api.md
重要:先阅读最佳实践
在实现广告代码之前,请阅读下方的最佳实践部分(步骤10之后)。其中包含加载策略、错误处理、内存管理和展示策略的重要模式。这些模式应融入所有广告实现中。
实现检查点:
在实现广告单元之前,请确认:
"在提供广告实现代码之前,请确认:
- 你是否已完成步骤7中的SDK初始化?
- 你是否在Unity控制台中收到'LevelPlay SDK initialized successfully'日志消息?
请在继续实现广告单元前验证初始化是否正常工作。"
如果用户回答否或不确定:
- 引导返回步骤7完成初始化
- 在确认初始化正常工作之前,不要提供广告实现代码
如果用户回答是,继续实现广告单元。
广告格式检查点——生成代码前询问:"你想要实现哪些广告格式?激励广告、插屏广告、横幅广告还是组合?"仅实现用户选择的格式。用户可稍后使用'后续添加更多广告格式'部分添加更多格式。
根据所选策略实现相应的广告格式。
实现灵活性:可一次实现一种格式或全部格式。选择现在要实现的格式,之后随时可添加更多格式(见下方'后续添加更多广告格式'部分)。
首先,询问用户希望如何组织广告代码。在用户回答前不要生成任何代码:
"你希望如何组织广告实现代码?"
-
每种广告格式使用独立的管理器脚本 - 创建单独的脚本,如、
RewardedAdManager.cs、InterstitialAdManager.cs(适合大型项目,关注点清晰分离)BannerAdManager.cs -
使用一个统一的AdManager脚本 - 创建单个处理所有广告格式(更简单,所有内容集中在一处)
AdManager.cs -
直接展示代码片段 - 提供实现代码,不封装到特定文件中,以便你按偏好集成
-
我已有广告管理器代码 - 审查并帮助修复/更新现有实现
根据用户的回答调整响应内容。
然后展示可选的竞价底价功能(选项4跳过——改为审查现有代码):
仅针对本次会话中要实现的格式展示竞价底价范围。参考起始范围:激励广告:$0.50–$2.00 | 插屏广告:$0.20–$1.00 | 横幅广告:$0.05–$0.20。仅包含要实现的格式的范围。
"可选——高级:竞价底价
大多数发布商最初会跳过此项,待有实际控制台数据后再添加。你可安全地跳过此项,稍后再返回配置。
如果你现在想设置竞价底价:竞价底价为每个广告单元设置最低竞价价格(美元)——提高平均eCPM,但可能降低填充率。起始范围:
[要实现的格式的范围]
请回复每种格式的数值,或直接说'skip'——你可随时添加此项。"
记录每种格式的答案。对于提供了数值的格式,在广告构造中加入。标记为'skip'的格式使用基本构造函数。
Config.Builder().SetBidFloor(...)如果用户选择选项4(现有代码):
- 询问:"请分享你现有的广告管理器代码以供审查"
- 等待用户提供代码
- 分析现有实现:
- 检查是否使用当前LevelPlay广告单元API(LevelPlayRewardedAd、LevelPlayInterstitialAd、LevelPlayBannerAd)
- 识别是否使用已弃用的IronSource.Agent API
- 检查是否正确注册/取消订阅回调
- 查找缺少的错误处理或内存泄漏
- 提供具体指导:
- 如果使用已弃用的API:"你正在使用旧版IronSource.Agent API。以下是迁移到新版LevelPlay广告单元API的方法:"
- 如果使用当前API但存在问题:"你的实现看起来不错,但我注意到[具体问题]。以下是修复方法:"
- 如果实现正确:"你的实现很可靠。你想要添加哪些额外的广告格式?"
- 提供两种选择:
- 提供代码片段以集成到现有文件中进行修复
- 如果代码存在结构问题,建议重构
- 在审查现有代码后添加新格式时,仅针对这些新格式展示竞价底价提示,确认是否匹配现有代码组织模式或使用新模式,然后遵循选项1–3的相同实现指南。
对于每种广告格式,请遵循详细参考中的实现指南:
- 激励广告:见
references/rewarded-api.md - 插屏广告:见
references/interstitial-api.md - 横幅广告:见
references/banner-api.md
General Implementation Pattern
通用实现模式
All ad formats follow a similar lifecycle:
- Load: Request an ad from LevelPlay
- Listen: Register callbacks for ad events (loaded, failed, shown, clicked, closed)
- Check readiness: Verify ad is ready before showing
- Show: Display the ad to the user
- Handle callbacks: Respond to user interactions and ad lifecycle events
所有广告格式遵循类似的生命周期:
- 加载:向LevelPlay请求广告
- 监听:注册广告事件回调(加载完成、加载失败、展示、点击、关闭)
- 检查就绪状态:展示前验证广告是否就绪
- 展示:向用户展示广告
- 处理回调:响应用户交互和广告生命周期事件
Code Generation Guidelines
代码生成指南
If the user mentions they have existing code, ask to see it before providing implementation guidance. This allows you to provide targeted fixes rather than generating new code from scratch.
Adapt output based on the user's chosen organization approach:
Option 1: Separate manager scripts
- Create complete, production-ready files for each ad format
.cs - Name them clearly: ,
RewardedAdManager.cs,InterstitialAdManager.csBannerAdManager.cs - Include full class structure with proper namespaces
- Each manager handles one ad format completely
Option 2: Unified AdManager
- Create a single file
AdManager.cs - Include methods and callbacks for all requested ad formats in one class
- Use clear method naming to distinguish between formats (e.g., ,
LoadRewardedAd())LoadInterstitial() - Keep code organized with regions or comments separating each ad format
Option 3: Code snippets only
- Provide focused code blocks without full class wrappers
- Clearly label each snippet (e.g., "Rewarded Ad Initialization", "Interstitial Event Callbacks")
- Explain where/how to integrate each snippet
- Note any dependencies between snippets
Regardless of chosen approach, always include:
- All manager classes must inherit from — required for Unity lifecycle methods (
MonoBehaviour,Start()) and to attach the script to a GameObjectOnDestroy() - After generating any manager script, instruct the user to attach it to a persistent GameObject in their scene (the same one as the initializer, with )
DontDestroyOnLoad - For banner and interstitial managers, call in
DestroyAd()so ads are destroyed and memory is freed when the manager is destroyedOnDestroy() - Proper event subscription and unsubscription (to avoid memory leaks)
- Null checks and defensive programming
- Debug logs for troubleshooting
- Clear variable names that match LevelPlay conventions
- Error handling and graceful degradation
Bid floor handling (per-format):
- If the user provided a bid floor value for a format, wrap construction in and pass the config to the constructor.
Config.Builder().SetBidFloor(value).Build() - If the user said 'skip' for that format, use the basic constructor ().
new LevelPlayRewardedAd(adUnitId) - Apply per-format: a publisher may set a floor on rewarded but skip banner.
Example (with bid floor):
csharp
var config = new LevelPlayRewardedAd.Config.Builder()
.SetBidFloor(0.80)
.Build();
rewardedAd = new LevelPlayRewardedAd(adUnitId, config);Example (skipped):
csharp
rewardedAd = new LevelPlayRewardedAd(adUnitId);Impression Level Revenue Tracking: If the user answered Yes or Not Sure to ILRD in Step 7, the ILRD callback was wired up in the init script. See to forward the data to the analytics platform (Firebase, AppsFlyer, Adjust, Singular, or custom backend).
references/ilrd-api.mdIf the user said "No" to ILRD and wants to add it now, see — subscribe to before the existing call.
references/ilrd-api.mdLevelPlay.OnImpressionDataReadyLevelPlay.Init()如果用户提到已有代码,请在提供实现指导前查看代码。这样可提供针对性的修复,而非从头生成新代码。
根据用户选择的组织方式调整输出:
选项1:独立管理器脚本
- 为每种广告格式创建完整的、可用于生产环境的文件
.cs - 命名清晰:、
RewardedAdManager.cs、InterstitialAdManager.csBannerAdManager.cs - 包含完整的类结构和正确的命名空间
- 每个管理器完全处理一种广告格式
选项2:统一AdManager
- 创建单个文件
AdManager.cs - 在一个类中包含所有请求的广告格式的方法和回调
- 使用清晰的方法命名区分不同格式(例如、
LoadRewardedAd())LoadInterstitial() - 使用区域或注释分隔每种广告格式,保持代码组织有序
选项3:仅代码片段
- 提供聚焦的代码块,不包含完整的类包装
- 清晰标记每个片段(例如"激励广告初始化"、"插屏广告事件回调")
- 说明如何集成每个片段
- 注意片段之间的依赖关系
无论选择哪种方式,始终包含:
- 所有管理器类必须继承自——这是Unity生命周期方法(
MonoBehaviour、Start())和将脚本附加到GameObject所必需的OnDestroy() - 生成任何管理器脚本后,指导用户将其附加到场景中的持久化GameObject上(与初始化器相同,带有)
DontDestroyOnLoad - 对于横幅和插屏管理器,在中调用
OnDestroy(),以便管理器销毁时广告也被销毁并释放内存DestroyAd() - 正确的事件订阅和取消订阅(避免内存泄漏)
- 空值检查和防御性编程
- 用于故障排除的调试日志
- 符合LevelPlay约定的清晰变量名
- 错误处理和优雅降级
竞价底价处理(按格式):
- 如果用户为某格式提供了竞价底价值,将构造封装在中,并将配置传递给构造函数。
Config.Builder().SetBidFloor(value).Build() - 如果用户对该格式说'skip',使用基本构造函数()。
new LevelPlayRewardedAd(adUnitId) - 按格式应用:发布商可能为激励广告设置底价,但跳过横幅广告。
示例(带竞价底价):
csharp
var config = new LevelPlayRewardedAd.Config.Builder()
.SetBidFloor(0.80)
.Build();
rewardedAd = new LevelPlayRewardedAd(adUnitId, config);示例(跳过):
csharp
rewardedAd = new LevelPlayRewardedAd(adUnitId);展示级收入追踪:如果用户在步骤7中回答是或不确定ILRD,ILRD回调已在初始化脚本中配置。请查看以将数据转发到分析平台(Firebase、AppsFlyer、Adjust、Singular或自定义后端)。
references/ilrd-api.md如果用户之前对ILRD回答"否",现在想要添加,请查看——在现有调用之前订阅。
references/ilrd-api.mdLevelPlay.Init()LevelPlay.OnImpressionDataReady10. Testing and Validation
10. 测试与验证
LevelPlay provides two validation approaches for different stages of development:
LevelPlay提供两种验证方法,适用于不同的开发阶段:
Early Development: Mock Ads in Unity Editor
早期开发:Unity编辑器中的模拟广告
For early iteration and callback testing, use mock ads in Unity Editor. Unity automatically provides mock ads when you press Play in the Editor - no special configuration needed.
How it works:
When you press Play in Unity Editor, Unity automatically provides mock ads - no special configuration needed. Mock ads work with ANY App Key and Ad Unit ID values (including dummy values like "test" or "editor"). However, recommend using real App Key and real Ad Unit IDs from the LevelPlay dashboard so you don't forget to update them before building to device.
Example setup (works in both Editor and device builds):
The same initialization code you wrote in Step 7 works in both Editor (with mock ads) and device builds (with real ads). For example:
csharp
// Initialize with your actual App Key (replace "abc123..." with yours)
// Mock ads work with any value, but use your real key to avoid forgetting to update it later
LevelPlay.Init("abc123youractualappkey");Example for rewarded ads (works in both Editor and device):
csharp
// In OnInitSuccess callback:
// Use your real ad unit ID from LevelPlay dashboard (replace "12345..." with yours)
// Mock ads work with any value, but use your real IDs to avoid forgetting to update them later
LevelPlayRewardedAd rewardedAd = new LevelPlayRewardedAd("12345youractualadunitid");
rewardedAd.OnAdLoaded += OnAdLoaded;
rewardedAd.OnAdRewarded += OnAdRewarded;
rewardedAd.LoadAd();Key points:
- Mock ads work with any App Key/Ad Unit ID values (you can even use "test" or "editor")
- Recommended: Use your real credentials from Step 5 to avoid forgetting to update them later
- Mock ads appear automatically when testing in Unity Editor
- Real ads appear automatically when building to device
- Same code works everywhere - no switching or conditional compilation needed
- Android API 33+: If targeting Android 13+ devices, verify you've added the AD_ID permission to AndroidManifest.xml (see Step 4)
What mock ads validate:
- Ad integration flow works correctly
- Most callbacks fire as expected (see callback behavior below)
- Ad loading, showing, and closing logic
- Ad positioning and layout (for banners)
- Basic ad logic and state management
Mock ad callback behavior:
Mock ads in Unity Editor fire most callbacks, but not all:
Callbacks that FIRE:
- - Always fires after LoadAd()
OnAdLoaded - - Fires when ShowAd() is called
OnAdDisplayed - - Fires for rewarded ads (with test reward)
OnAdRewarded - - Fires when mock ad is dismissed
OnAdClosed
Callbacks that DON'T fire:
- - Mock ads always succeed loading
OnAdLoadFailed - - Mock ads always succeed showing
OnAdDisplayFailed - - Mock ads don't simulate user clicks
OnAdClicked - /
OnAdExpanded- Banner expand/collapse not simulatedOnAdCollapsed - - No real ad redirect in Editor
OnAdLeftApplication - - Mock ads don't update ad info dynamically
OnAdInfoChanged - (ILRD) - No impression data generated in Editor
LevelPlay.OnImpressionDataReady
This means you can test your happy-path flow in Editor, but must test error handling on real devices.
Note on SDK initialization in the Editor: may not fire in all SDK configurations when running in the Unity Editor. If your initialization callback doesn't trigger and your ad objects never load as a result, try creating them directly in after calling rather than waiting for the callback — mock ads will appear even without firing.
LevelPlay.OnInitSuccessStart()LevelPlay.Init()OnInitSuccessMock ads limitations:
- Don't simulate network latency or failures
- Don't test real ad network behavior
- Don't validate reward logic server-side
- Placeholder UI instead of real ad creatives
- Error callbacks never fire
Best for: Early development, rapid iteration on ad logic, callback testing
对于早期迭代和回调测试,在Unity编辑器中使用模拟广告。在编辑器中按Play时,Unity会自动提供模拟广告——无需特殊配置。
工作原理:
在Unity编辑器中按Play时,Unity会自动提供模拟广告——无需特殊配置。模拟广告可与任何App Key和Ad Unit ID值配合使用(包括"test"或"editor"等虚拟值)。不过,建议使用LevelPlay控制台中的真实App Key和真实Ad Unit ID,以免在构建到设备前忘记更新。
示例设置(在编辑器和设备构建中均有效):
步骤7中编写的初始化代码在编辑器(使用模拟广告)和设备构建(使用真实广告)中均有效。例如:
csharp
// 使用你的实际App Key初始化(将"abc123..."替换为你的密钥)
// 模拟广告可与任何值配合使用,但使用真实密钥可避免稍后忘记更新
LevelPlay.Init("abc123youractualappkey");激励广告示例(在编辑器和设备中均有效):
csharp
// 在OnInitSuccess回调中:
// 使用LevelPlay控制台中的真实广告单元ID(将"12345..."替换为你的ID)
// 模拟广告可与任何值配合使用,但使用真实ID可避免稍后忘记更新
LevelPlayRewardedAd rewardedAd = new LevelPlayRewardedAd("12345youractualadunitid");
rewardedAd.OnAdLoaded += OnAdLoaded;
rewardedAd.OnAdRewarded += OnAdRewarded;
rewardedAd.LoadAd();关键点:
- 模拟广告可与任何App Key/Ad Unit ID值配合使用(甚至可使用"test"或"editor")
- 推荐:使用步骤5中的真实凭据,以免稍后忘记更新
- 模拟广告在Unity编辑器中自动显示
- 真实广告在设备构建中自动显示
- 相同代码适用于所有环境——无需切换或条件编译
- Android API 33+:如果针对Android 13+设备,请确认已将AD_ID权限添加到AndroidManifest.xml(见步骤4)
模拟广告验证内容:
- 广告集成流程正常工作
- 大多数回调按预期触发(见下方回调行为)
- 广告加载、展示和关闭逻辑
- 广告定位和布局(针对横幅广告)
- 基本广告逻辑和状态管理
模拟广告回调行为:
Unity编辑器中的模拟广告会触发大多数回调,但并非全部:
会触发的回调:
- - 调用LoadAd()后始终触发
OnAdLoaded - - 调用ShowAd()时触发
OnAdDisplayed - - 针对激励广告触发(带有测试奖励)
OnAdRewarded - - 模拟广告关闭时触发
OnAdClosed
不会触发的回调:
- - 模拟广告加载始终成功
OnAdLoadFailed - - 模拟广告展示始终成功
OnAdDisplayFailed - - 模拟广告不模拟用户点击
OnAdClicked - /
OnAdExpanded- 不模拟横幅广告的展开/折叠OnAdCollapsed - - 编辑器中无真实广告重定向
OnAdLeftApplication - - 模拟广告不动态更新广告信息
OnAdInfoChanged - (ILRD) - 编辑器中不生成展示数据
LevelPlay.OnImpressionDataReady
这意味着你可在编辑器中测试正常流程,但必须在真实设备上测试错误处理。
注意编辑器中的SDK初始化:在某些SDK配置下,在Unity编辑器中可能不会触发。如果初始化回调未触发且广告对象始终无法加载,可尝试在调用后直接在中创建广告对象,而非等待回调——即使未触发,模拟广告也会显示。
LevelPlay.OnInitSuccessLevelPlay.Init()Start()OnInitSuccess模拟广告限制:
- 不模拟网络延迟或故障
- 不测试真实广告网络行为
- 不验证服务器端奖励逻辑
- 使用占位符UI而非真实广告素材
- 错误回调从不触发
最适合:早期开发、广告逻辑快速迭代、回调测试
Integration Validation: LevelPlay Test Suite (Recommended)
集成验证:LevelPlay测试套件(推荐)
The Test Suite is the primary method for comprehensive validation. It tests your integration with real ad networks on device.
What Test Suite validates:
- All ad formats (Rewarded, Interstitial, Banner) with real ads
- SDK initialization with production App Key
- All callbacks fire correctly in production environment
- Real ad network behavior, latency, and edge cases
- Ad rendering and user interaction flows
Before running the Test Suite:
- Unity Ads is pre-installed — the Ads Mediation package includes the Unity Ads adapter by default, so you have at least one network ready without any additional setup. For ads to fill on device, verify your LevelPlay dashboard has active instances configured for your ad units.
- Enable Development Build in Build Profiles (called Build Settings in Unity versions before Unity 6) before building to device. Without it, SDK console output won't be visible, making it very difficult to diagnose issues if something doesn't work as expected.
Setup (requires device build):
Add these two lines to your existing — do not create a new file or replace your existing initializer:
LevelPlayInitializer.cs- At the top of , before
Start():LevelPlay.Init(appKey)
csharp
LevelPlay.SetMetaData("is_test_suite", "enable");- Inside your callback:
OnInitSuccess
csharp
LevelPlay.LaunchTestSuite();Important: Remove both lines before your production release. Test Suite should only be used during development and testing.
Don't have a yet? Use this complete template:
LevelPlayInitializer.cscsharp
using UnityEngine;
using Unity.Services.LevelPlay;
public class LevelPlayInitializer : MonoBehaviour
{
[SerializeField] private string appKey;
void Awake()
{
DontDestroyOnLoad(gameObject);
}
void Start()
{
// Enable Test Suite — REMOVE before production release
LevelPlay.SetMetaData("is_test_suite", "enable");
LevelPlay.OnInitSuccess += OnInitSuccess;
LevelPlay.OnInitFailed += OnInitFailed;
LevelPlay.Init(appKey);
}
private void OnInitSuccess(LevelPlayConfiguration config)
{
Debug.Log("LevelPlay initialized successfully");
// Launch Test Suite — REMOVE before production release
LevelPlay.LaunchTestSuite();
}
private void OnInitFailed(LevelPlayInitError error)
{
Debug.LogError($"LevelPlay initialization failed: {error.ErrorMessage}");
}
void OnDestroy()
{
LevelPlay.OnInitSuccess -= OnInitSuccess;
LevelPlay.OnInitFailed -= OnInitFailed;
}
}After creating this script:
- Attach it to a GameObject in your first scene
- In the Unity Inspector, find the "App Key" field
- Paste your App Key from Step 5 into that field
Key points:
- must be called BEFORE
LevelPlay.SetMetaData("is_test_suite", "enable");— if the Test Suite doesn't appear after launch, this is the most likely causeLevelPlay.Init() - is called AFTER successful initialization (in
LevelPlay.LaunchTestSuite();)OnInitSuccess - Requires device build - Test Suite does not work in Unity Editor
- Use production App Key, not "editor"
- Build to Android or iOS device and run the app
- Test Suite UI will appear automatically after initialization
Testing workflow:
- Add Test Suite code (SetMetaData before Init, LaunchTestSuite after OnInitSuccess)
- Build to Android or iOS device
- Run the app on device
- Test Suite UI launches automatically
- Follow on-screen instructions to test each ad format
- Verify all ad formats load and callbacks fire correctly
Best for: Integration validation before production, final testing with real ad networks
测试套件是全面验证的主要方法。它在设备上测试与真实广告网络的集成。
测试套件验证内容:
- 所有广告格式(激励广告、插屏广告、横幅广告)与真实广告
- 使用生产环境App Key的SDK初始化
- 所有回调在生产环境中正确触发
- 真实广告网络行为、延迟和边缘情况
- 广告渲染和用户交互流程
运行测试套件前:
- Unity Ads已预安装——Ads Mediation包默认包含Unity Ads适配器,因此无需额外设置即可拥有至少一个可用网络。要在设备上获得广告填充,请确认LevelPlay控制台中为你的广告单元配置了活跃实例。
- 在Build Profiles(Unity 6之前的版本称为Build Settings)中启用Development Build,然后再构建到设备。如果不启用,SDK控制台输出将不可见,导致出现问题时难以诊断。
设置(需要设备构建):
将以下两行添加到现有的中——不要创建新文件或替换现有的初始化器:
LevelPlayInitializer.cs- 在顶部,
Start()之前:LevelPlay.Init(appKey)
csharp
LevelPlay.SetMetaData("is_test_suite", "enable");- 在回调中:
OnInitSuccess
csharp
LevelPlay.LaunchTestSuite();重要:在生产发布前删除这两行。测试套件仅应在开发和测试期间使用。
还没有? 使用以下完整模板:
LevelPlayInitializer.cscsharp
using UnityEngine;
using Unity.Services.LevelPlay;
public class LevelPlayInitializer : MonoBehaviour
{
[SerializeField] private string appKey;
void Awake()
{
DontDestroyOnLoad(gameObject);
}
void Start()
{
// Enable Test Suite — REMOVE before production release
LevelPlay.SetMetaData("is_test_suite", "enable");
LevelPlay.OnInitSuccess += OnInitSuccess;
LevelPlay.OnInitFailed += OnInitFailed;
LevelPlay.Init(appKey);
}
private void OnInitSuccess(LevelPlayConfiguration config)
{
Debug.Log("LevelPlay initialized successfully");
// Launch Test Suite — REMOVE before production release
LevelPlay.LaunchTestSuite();
}
private void OnInitFailed(LevelPlayInitError error)
{
Debug.LogError($"LevelPlay initialization failed: {error.ErrorMessage}");
}
void OnDestroy()
{
LevelPlay.OnInitSuccess -= OnInitSuccess;
LevelPlay.OnInitFailed -= OnInitFailed;
}
}创建此脚本后:
- 将其附加到第一个场景中的GameObject上
- 在Unity Inspector中找到"App Key"字段
- 将步骤5中的应用密钥粘贴到该字段中
关键点:
- 必须在
LevelPlay.SetMetaData("is_test_suite", "enable");之前调用——如果测试套件启动后未显示,这是最可能的原因LevelPlay.Init() - 在初始化成功后调用(在
LevelPlay.LaunchTestSuite();中)OnInitSuccess - 需要设备构建——测试套件在Unity编辑器中无法工作
- 使用生产环境App Key,而非"editor"
- 构建到Android或iOS设备并运行应用
- 初始化后测试套件UI会自动显示
测试工作流:
- 添加测试套件代码(Init前设置SetMetaData,OnInitSuccess后调用LaunchTestSuite)
- 构建到Android或iOS设备
- 在设备上运行应用
- 测试套件UI自动启动
- 按照屏幕说明测试每种广告格式
- 验证所有广告格式加载且回调正确触发
最适合:生产前的集成验证、与真实广告网络的最终测试
Production Release Checklist
生产发布检查清单
Before releasing to production:
- Test Suite validation completed successfully on device
- All ad formats load correctly (Rewarded, Interstitial, Banner if implemented)
- All callbacks fire as expected
- App Key and ad unit IDs verified correct for production
- Tested on multiple devices (different screen sizes, OS versions)
- iOS-specific requirements completed (if targeting iOS):
- SKAdNetwork IDs configured in Info.plist (see )
references/ios-setup.md - App Tracking Transparency (ATT) framework implemented (see )
references/ios-setup.md - iOS privacy manifest configured if required
- Tested on physical iOS device (not just simulator)
- SKAdNetwork IDs configured in Info.plist (see
- Android-specific requirements completed (if targeting Android):
- Google Play Services dependencies resolved (Step 4 completed)
- AD_ID permission added to AndroidManifest.xml if targeting API 33+ (see Step 4)
- Tested on physical Android device
- Tested with real ads in production environment
- Ad frequency capping implemented (if using interstitials)
- Error handling works correctly (test with airplane mode - ads should fail gracefully without crashing or blocking gameplay)
发布到生产环境前:
- 已在设备上成功完成测试套件验证
- 所有广告格式加载正常(已实现的激励广告、插屏广告、横幅广告)
- 所有回调按预期触发
- 已验证生产环境的App Key和广告单元ID正确
- 已在多个设备上测试(不同屏幕尺寸、OS版本)
- 已完成iOS特定要求(如果针对iOS):
- 已在Info.plist中配置SKAdNetwork ID(见)
references/ios-setup.md - 已实现App Tracking Transparency(ATT)框架(见)
references/ios-setup.md - 已配置iOS隐私清单(如需要)
- 已在物理iOS设备上测试(不仅是模拟器)
- 已在Info.plist中配置SKAdNetwork ID(见
- 已完成Android特定要求(如果针对Android):
- 已解决Google Play Services依赖项(已完成步骤4)
- 如果针对API 33+,已将AD_ID权限添加到AndroidManifest.xml(见步骤4)
- 已在物理Android设备上测试
- 已在生产环境中测试真实广告
- 已实现广告频率上限(如果使用插屏广告)
- 错误处理正常工作(测试飞行模式——广告应优雅失败,不会崩溃或阻塞游戏玩法)
Adding More Ad Formats Later
后续添加更多广告格式
If you've already integrated some ad formats and want to add more:
- Skip to Step 9 - You don't need to repeat the initial setup steps. Before proceeding, verify your existing initialization still works by checking the Unity console for the 'LevelPlay SDK initialized successfully' log.
- Choose the additional formats you want to implement
- Follow the same organization pattern you used before:
- If you created separate manager scripts, create a new manager script for the new format
- If you used a unified AdManager, add the new format's code to your existing AdManager class
- If you used code snippets, integrate new snippets following the same pattern
- Follow the same implementation guidelines from Step 9 for the new ad format
- Test the new format following Step 10 testing guidelines
Example: If you initially implemented only Rewarded ads using separate manager scripts, and now want to add Interstitial ads:
- Create following the same structure as your
InterstitialAdManager.csRewardedAdManager.cs - Follow the interstitial implementation guidelines from
references/interstitial-api.md - Test the interstitial ads in Unity Editor and on device
Your existing ad formats will continue to work while you add new ones. You can add formats incrementally without disrupting your current implementation.
如果你已集成部分广告格式,想要添加更多:
- 跳转到步骤9——无需重复初始设置步骤。继续前,请通过检查Unity控制台中的'LevelPlay SDK initialized successfully'日志,验证现有初始化仍正常工作。
- 选择要添加的额外格式
- 遵循之前使用的组织模式:
- 如果创建了独立的管理器脚本,为新格式创建新的管理器脚本
- 如果使用了统一的AdManager,将新格式的代码添加到现有AdManager类中
- 如果使用了代码片段,按照相同模式集成新片段
- 遵循步骤9中针对新广告格式的相同实现指南
- 按照步骤10的测试指南测试新格式
示例:如果你最初使用独立管理器脚本仅实现了激励广告,现在想要添加插屏广告:
- 按照的结构创建
RewardedAdManager.csInterstitialAdManager.cs - 遵循中的插屏广告实现指南
references/interstitial-api.md - 在Unity编辑器和设备上测试插屏广告
现有广告格式在添加新格式时将继续正常工作。你可逐步添加格式,不会干扰当前实现。
Best Practices
最佳实践
Loading Strategy
加载策略
Rewarded Ads:
- Load immediately after SDK initialization (load proactively means load early and keep ads preloaded)
- Reload immediately after showing or when ad fails to load
- Always keep a rewarded ad ready to show
Interstitial Ads:
- Load proactively before natural break points
- Maintain a loaded interstitial for opportunistic moments
- Reload after showing
Banner Ads:
- Load when entering scenes where banners will be displayed
- Destroy banners when leaving those scenes to free memory
激励广告:
- SDK初始化后立即加载(主动加载意味着提前加载并保持广告预加载状态)
- 展示后或广告加载失败时立即重新加载
- 始终保持一个激励广告可随时展示
插屏广告:
- 在自然断点前主动加载
- 保持一个已加载的插屏广告,以备不时之需
- 展示后重新加载
横幅广告:
- 进入要展示横幅广告的场景时加载
- 离开这些场景时销毁横幅广告以释放内存
Placement Strategy
展示策略
Align ad placements with user engagement moments:
- High engagement (post-victory, level up): Best for rewarded ads
- Natural transitions (level complete, menu navigation): Good for interstitials
- Low attention (waiting periods, menus): Acceptable for banners
将广告展示位置与用户参与时刻对齐:
- 高参与度(胜利后、升级时):最适合激励广告
- 自然过渡(关卡完成、菜单导航):适合插屏广告
- 低注意力(等待时间、菜单):可接受横幅广告
Error Handling
错误处理
Always handle ad load failures gracefully:
csharp
private void OnAdLoadFailed(LevelPlayAdError error)
{
Debug.LogWarning($"Ad failed to load: {error.ErrorMessage}");
// Retry loading after a delay
Invoke(nameof(LoadAd), 30f); // Retry in 30 seconds
// Provide fallback UX if ad was requested by user
// Don't leave users stuck waiting for an ad that won't load
}始终优雅处理广告加载失败:
csharp
private void OnAdLoadFailed(LevelPlayAdError error)
{
Debug.LogWarning($"Ad failed to load: {error.ErrorMessage}");
// 延迟后重试加载
Invoke(nameof(LoadAd), 30f); // 30秒后重试
// 如果用户请求了广告,提供备用用户体验
// 不要让用户一直等待无法加载的广告
}Memory Management
内存管理
Properly unsubscribe from events to prevent memory leaks:
csharp
void OnDestroy()
{
// Unsubscribe from all LevelPlay events
if (rewardedAd != null)
{
rewardedAd.OnAdLoaded -= OnAdLoaded;
rewardedAd.OnAdLoadFailed -= OnAdLoadFailed;
// ... unsubscribe from all other events
}
}正确取消订阅事件以防止内存泄漏:
csharp
void OnDestroy()
{
// 取消订阅所有LevelPlay事件
if (rewardedAd != null)
{
rewardedAd.OnAdLoaded -= OnAdLoaded;
rewardedAd.OnAdLoadFailed -= OnAdLoadFailed;
// ... 取消订阅所有其他事件
}
}Common Issues and Solutions
常见问题与解决方案
Note: This section addresses issues that can occur during integration. If you haven't started the integration yet, begin with Step 1: Verify Environment.
注意:本节解决集成过程中可能出现的问题。如果你尚未开始集成,请从步骤1:验证环境开始。
Issue: CS0246 - Type or namespace 'Unity.Services.LevelPlay' not found
问题:CS0246 - 找不到类型或命名空间'Unity.Services.LevelPlay'
Root cause: Ads Mediation package not installed in Unity project
Symptoms:
- Compiler errors:
The type or namespace name 'LevelPlay' could not be found - Compiler errors:
The type or namespace name 'Unity.Services.LevelPlay' could not be found - Red underlines in Unity Editor on all LevelPlay code
Solutions:
- Stop providing code immediately
- Ask: "Can you confirm the Ads Mediation package is installed? Check Window > Package Manager and verify 'Ads Mediation' appears under 'Packages: In Project'"
- If not installed, direct to Step 3 to install via Unity Package Manager
- Have them restart Unity Editor after installation (important!)
- Verify installation by checking that no longer shows errors
using Unity.Services.LevelPlay; - Only resume code generation after confirmation and verification
Prevention: Always verify package installation at Step 7 checkpoint before generating any code.
根本原因:Unity项目中未安装Ads Mediation包
症状:
- 编译器错误:
The type or namespace name 'LevelPlay' could not be found - 编译器错误:
The type or namespace name 'Unity.Services.LevelPlay' could not be found - Unity编辑器中所有LevelPlay代码下出现红色下划线
解决方案:
- 立即停止提供代码
- 询问:"你能否确认已安装Ads Mediation包?请检查Window > Package Manager并确认'Ads Mediation'出现在'Packages: In Project'下"
- 如果未安装,引导至步骤3通过Unity Package Manager安装
- 安装后重启Unity编辑器(重要!)
- 通过检查不再显示错误来验证安装
using Unity.Services.LevelPlay; - 仅在确认和验证后恢复代码生成
预防:在步骤7检查点始终验证包安装,然后再生成任何代码。
Issue: Android gradle build fails / iOS build fails with dependency errors
问题:Android gradle构建失败 / iOS构建出现依赖项错误
Root cause: Native dependencies not resolved
Symptoms:
- Android: Gradle build errors mentioning missing dependencies or classes
- iOS: CocoaPods errors, missing frameworks, or linker errors
- Code compiles perfectly in Unity Editor but fails during platform build
- Build succeeds in Editor but crashes immediately on device
Solutions:
- Verify you have a dependency manager installed (Mobile Dependency Resolver, Unity External Dependency Manager, or EDM4U)
- Check your project's Assets folder for dependency manager tools
- Run dependency resolution:
- Android (newer MDR versions): Should auto-resolve on build. If failing, manually resolve via Assets > Mobile Dependency Resolver > Android Resolver > Resolve
- Android (older/other managers): Assets > [Your Dependency Manager] > Android Resolver > Resolve
- iOS (all managers): Assets > [Your Dependency Manager] > iOS Resolver > Install Cocoapods
- Verify resolution:
- Android: Check for gradle files
Assets/Plugins/Android/ - iOS: Look for Podfile or CocoaPods confirmation in console
- Android: Check
- If you don't have a dependency manager, restart Unity - you should see a prompt to install Mobile Dependency Resolver
- Rebuild for your target platform after resolution
Prevention: Complete Step 4 (dependency resolution) before building for Android/iOS.
根本原因:未解决原生依赖项
症状:
- Android:Gradle构建错误提及缺少依赖项或类
- iOS:CocoaPods错误、缺少框架或链接器错误
- 代码在Unity编辑器中编译完美,但平台构建失败
- 编辑器中构建成功,但在设备上立即崩溃
解决方案:
- 验证是否安装了依赖项管理器(Mobile Dependency Resolver、Unity External Dependency Manager或EDM4U)
- 检查项目的Assets文件夹中是否有依赖项管理器工具
- 运行依赖项解决:
- Android(新版MDR):构建时应自动解决。如果失败,通过Assets > Mobile Dependency Resolver > Android Resolver > Resolve手动解决
- Android(旧版/其他管理器):Assets > [你的依赖项管理器] > Android Resolver > Resolve
- iOS(所有管理器):Assets > [你的依赖项管理器] > iOS Resolver > Install Cocoapods
- 验证解决结果:
- Android:检查中的gradle文件
Assets/Plugins/Android/ - iOS:查看控制台中的Podfile或CocoaPods确认信息
- Android:检查
- 如果没有依赖项管理器,重启Unity——应会看到安装Mobile Dependency Resolver的提示
- 解决后重新构建目标平台
预防:在构建Android/iOS之前完成步骤4(依赖项解决)。
Issue: Ads not loading
问题:广告无法加载
Possible causes:
- SDK not initialized before loading ads
- Incorrect App Key
- Ad object created before initialization completes
- Network connectivity issues
- Ad inventory not available in test region
Solutions:
- Verify is called and
LevelPlay.Init()fires before creating ad objectsOnInitSuccess - Create ad objects only after callback
OnInitSuccess - Check App Key matches LevelPlay dashboard
- Test on real devices with active internet connection
- Enable test mode in LevelPlay dashboard for guaranteed test ads (Note: dashboard test mode is separate from mock ads in the Unity Editor — it enables real test ads on device)
可能原因:
- 加载广告前未初始化SDK
- App Key错误
- 初始化完成前创建了广告对象
- 网络连接问题
- 测试区域无广告库存
解决方案:
- 验证已调用且
LevelPlay.Init()触发后再创建广告对象OnInitSuccess - 仅在回调后创建广告对象
OnInitSuccess - 检查App Key与LevelPlay控制台匹配
- 在有活跃互联网连接的真实设备上测试
- 在LevelPlay控制台中启用测试模式以获取测试广告(注意:控制台测试模式与Unity编辑器中的模拟广告不同——它在设备上启用真实测试广告)
Issue: Callbacks not firing
问题:回调未触发
Possible causes:
- Events registered after SDK initialization
- Missing event subscriptions
- Script destroyed before callbacks execute
Solutions:
- Register callbacks before calling
Init() - Verify all callbacks are subscribed (check with Debug.Log statements)
- Use persistent GameObject with DontDestroyOnLoad if needed
可能原因:
- SDK初始化后注册事件
- 缺少事件订阅
- 回调执行前脚本已销毁
解决方案:
- 调用前注册回调
Init() - 验证所有回调已订阅(使用Debug.Log语句检查)
- 如果需要,使用带有DontDestroyOnLoad的持久化GameObject
Issue: Platform-specific build errors
问题:特定平台构建错误
iOS:
- Ensure SKAdNetwork IDs are configured in Info.plist
- Verify ATT is implemented correctly (see )
references/ios-setup.md - Check Xcode build settings for required frameworks
Android:
- Verify Google Play Services is included
- Check AndroidManifest.xml for required permissions
- Ensure Gradle dependencies are resolved
iOS:
- 确保已在Info.plist中配置SKAdNetwork ID
- 验证ATT已正确实现(见)
references/ios-setup.md - 检查Xcode构建设置中的必需框架
Android:
- 验证已包含Google Play Services
- 检查AndroidManifest.xml中的必需权限
- 确保已解决Gradle依赖项
When to Read Detailed References
何时阅读详细参考
Read specific references based on what the user is implementing:
- : When implementing rewarded ads
references/rewarded-api.md - : When implementing interstitial ads
references/interstitial-api.md - : When implementing banner ads
references/banner-api.md - : When user ID tracking, segmentation, consent management, or advanced SDK configuration options are needed
references/initialization-api.md - : When targeting iOS builds
references/ios-setup.md - : When user asks for optimization guidance or troubleshooting
references/best-practices.md - : When GDPR, CCPA, or COPPA compliance is needed
references/privacy-settings.md - : When wiring ILRD to an analytics platform
references/ilrd-api.md
根据用户正在实现的内容阅读特定参考:
- :实现激励广告时
references/rewarded-api.md - :实现插屏广告时
references/interstitial-api.md - :实现横幅广告时
references/banner-api.md - :需要用户ID追踪、细分、同意管理或高级SDK配置选项时
references/initialization-api.md - :针对iOS构建时
references/ios-setup.md - :用户询问优化指导或故障排除时
references/best-practices.md - :需要GDPR、CCPA或COPPA合规时
references/privacy-settings.md - :将ILRD连接到分析平台时
references/ilrd-api.md
Examples
示例
Note: These examples show abbreviated workflows for illustration. In practice, follow all steps 1–10 in order to ensure proper integration.
注意:这些示例展示了简化的工作流,仅供说明。实际操作中,请按顺序遵循所有步骤1–10以确保正确集成。
Example 1: Revenue-Focused Game
示例1:以收入为导向的游戏
User request: "I want to maximize ad revenue in my casual puzzle game"
Response approach:
- Verify Unity project (Step 1)
- Ask about optimization goal (Step 2)
- Verify SDK installed (Step 3)
- Verify dependencies resolved (Step 4)
- Verify they have App Key (Step 5)
- Verify AdMob config if needed (Step 6)
- Verify SDK initialized (Step 7)
- Recommend revenue-focused strategy (Step 8)
- Ask about code organization preference (Step 9)
- Generate appropriate code structure (Step 9)
- Guide through testing (Step 10)
用户请求:"我想最大化休闲益智游戏的广告收入"
响应方法:
- 验证Unity项目(步骤1)
- 询问优化目标(步骤2)
- 验证SDK已安装(步骤3)
- 验证依赖项已解决(步骤4)
- 验证用户拥有App Key(步骤5)
- 验证AdMob配置(如需要)(步骤6)
- 验证SDK已初始化(步骤7)
- 推荐以收入为导向的策略(步骤8)
- 询问代码组织偏好(步骤9)
- 生成适当的代码结构(步骤9)
- 指导测试(步骤10)
Example 2: UX-Focused Game
示例2:以用户体验为导向的游戏
User request: "I want to add optional rewarded ads for extra lives without annoying players"
Response approach:
- Verify Unity project (Step 1)
- Ask about optimization goal (Step 2)
- Verify SDK installed (Step 3)
- Verify dependencies resolved (Step 4)
- Verify they have App Key (Step 5)
- Verify AdMob config if needed (Step 6)
- Verify SDK initialized (Step 7)
- Recommend UX-focused strategy (Step 8): Rewarded only, user-initiated
- Ask about code organization preference (Step 9)
- Provide implementation with proper patterns (Step 9)
- Guide through testing (Step 10)
用户请求:"我想添加可选的激励广告以提供额外生命,同时不打扰玩家"
响应方法:
- 验证Unity项目(步骤1)
- 询问优化目标(步骤2)
- 验证SDK已安装(步骤3)
- 验证依赖项已解决(步骤4)
- 验证用户拥有App Key(步骤5)
- 验证AdMob配置(如需要)(步骤6)
- 验证SDK已初始化(步骤7)
- 推荐以用户体验为导向的策略(步骤8):仅激励广告,用户主动触发
- 询问代码组织偏好(步骤9)
- 提供带有正确模式的实现(步骤9)
- 指导测试(步骤10)
Example 3: Existing Project Integration
示例3:现有项目集成
User request: "I have an existing GameManager script and want to add interstitial ads between levels"
Response approach:
- Verify Unity project (Step 1)
- Ask about optimization goal (Step 2)
- Verify SDK installed (Step 3)
- Verify dependencies resolved (Step 4)
- Verify they have App Key (Step 5)
- Verify AdMob config if needed (Step 6)
- Verify SDK initialized (Step 7)
- Recommend balanced strategy (Step 8)
- Ask to see existing GameManager.cs, then provide code snippets (Step 9)
- Guide through testing (Step 10)
用户请求:"我有一个现有的GameManager脚本,想要在关卡之间添加插屏广告"
响应方法:
- 验证Unity项目(步骤1)
- 询问优化目标(步骤2)
- 验证SDK已安装(步骤3)
- 验证依赖项已解决(步骤4)
- 验证用户拥有App Key(步骤5)
- 验证AdMob配置(如需要)(步骤6)
- 验证SDK已初始化(步骤7)
- 推荐平衡型策略(步骤8)
- 请求查看现有的GameManager.cs,然后提供代码片段(步骤9)
- 指导测试(步骤10)