diff --git a/skills/using-unity/SKILL.md b/skills/using-unity/SKILL.md index dcd78f7..76f035c 100644 --- a/skills/using-unity/SKILL.md +++ b/skills/using-unity/SKILL.md @@ -38,7 +38,7 @@ A skill may tell you to use, load or check for another skill by name, for exampl - **import-and-optimize-cad-models**: Imports and optimizes CAD models and point clouds with Asset Transformer Toolkit (Pixyz). Make sure to use this skill when the user wants to import CAD or point cloud files, or build RuleSets, Actions, or LODs for them. File: `references/import-and-optimize-cad-models/import-and-optimize-cad-models.md` - **initialize-ai-navigation**: Sets up and configures Unity AI Navigation, including NavMesh surfaces, agents, obstacles, and links. Use when the user asks about navigation meshes, pathfinding, patrol routes, or obstacle avoidance. File: `references/initialize-ai-navigation/initialize-ai-navigation.md` - **instrument-game-telemetry**: Adds telemetry events to a Unity game with the Insights Events package, covering retention, level difficulty and economy balance. Use to instrument, add, extend, retrofit or fix game analytics, telemetry or tracking, or to migrate from Firebase, GA4 or AppsFlyer. Not for querying or exporting data already collected. File: `references/instrument-game-telemetry/instrument-game-telemetry.md` -- **levelplay-unity-integration**: Integrates the LevelPlay ad mediation SDK via the Ads Mediation package. Use when the user asks about adding rewarded, interstitial, or banner ads, mediation or ad privacy setup, Android or iOS ad dependency build failures, or migrating from Unity Ads or IronSource APIs. File: `references/levelplay-unity-integration/levelplay-unity-integration.md` +- **levelplay-unity-integration**: Integrates the LevelPlay ad mediation SDK (Ads Mediation package). Use for where ads belong in a game, rewarded, interstitial or banner ads, mediation or privacy setup, Android or iOS ad build failures, or migrating from Unity Ads or IronSource. File: `references/levelplay-unity-integration/levelplay-unity-integration.md` - **localize-unity-project**: Sets up Unity Localization, including locales, String and Asset Tables, and CJK fonts. Use when the user wants to add languages or translate UI text. File: `references/localize-unity-project/localize-unity-project.md` - **manage-sprite-atlas**: Manages SpriteAtlas assets through a prebuild pipeline, covering master and variant atlases, packing settings, and platform overrides. Use when asked to create or optimize sprite atlases. File: `references/manage-sprite-atlas/manage-sprite-atlas.md` - **migrate-birp-to-urp**: Plans, executes, and troubleshoots migration from the Built-in Render Pipeline to URP. Use when asked to convert a project, scene, material, or shader to URP, or to fix visuals broken by the change. File: `references/migrate-birp-to-urp/migrate-birp-to-urp.md` diff --git a/skills/using-unity/references/levelplay-unity-integration/levelplay-unity-integration.md b/skills/using-unity/references/levelplay-unity-integration/levelplay-unity-integration.md index 2a55146..b9ac408 100644 --- a/skills/using-unity/references/levelplay-unity-integration/levelplay-unity-integration.md +++ b/skills/using-unity/references/levelplay-unity-integration/levelplay-unity-integration.md @@ -1,6 +1,6 @@ --- name: levelplay-unity-integration -description: Integrates the LevelPlay ad mediation SDK via the Ads Mediation package. Use when the user asks about adding rewarded, interstitial, or banner ads, mediation or ad privacy setup, Android or iOS ad dependency build failures, or migrating from Unity Ads or IronSource APIs. +description: Integrates the LevelPlay ad mediation SDK (Ads Mediation package). Use for where ads belong in a game, rewarded, interstitial or banner ads, mediation or privacy setup, Android or iOS ad build failures, or migrating from Unity Ads or IronSource. --- # LevelPlay Unity package/SDK Integration @@ -11,7 +11,7 @@ This skill covers the LevelPlay integration path only; it does not cover other m Follow the steps and provide only the files and configurations described in this skill. Do not proactively add steps, create files, or make recommendations based on general knowledge. If the user asks a question outside the scope of this skill, check the skill and reference files first to confirm it is not covered. If it is not, use general knowledge to respond, but do not incorporate additional steps or files into the integration workflow as a result. -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. +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. The Step 2 project profile is read from files, not asked. 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. @@ -21,27 +21,36 @@ LevelPlay is Unity's ad mediation platform: it connects your game to multiple ad ### 0. New Integration or Migration? -Ask: "Are you starting a new LevelPlay integration, migrating an existing one (from an older SDK version or from Unity Ads), or troubleshooting an existing setup?" +Ask: "Are you starting a new LevelPlay integration, migrating an existing one (from an older SDK version or from Unity Ads), troubleshooting an existing setup, or only asking where ads should go in your game?" If the user's message already answers this (for example it only asks where ads belong), take that path without asking. - **New integration**: proceed to Step 1. - **Migration** (SDK upgrade, replacing IronSource.Agent APIs, migrating from Unity Ads, or fixing a Maven Central Android build failure): Read `references/migration-sdk-9.md`. Ask which of the five scenarios applies — A = SDK upgrade, B = init API migration, C = ad unit API migration, D = Maven Central build failure, E = Unity Ads migration — then follow the matching scenario. After applying all code changes, work through the Migration Completeness Checklist (section C5 of the reference) — it catches requirements that a line-by-line translation misses because the legacy code had no equivalent line. Then ask the user to check the Unity console for compilation errors, and fix any that appear before presenting results. Do not block or keep retrying if you cannot see the console: list the files you changed, say what to look for, and continue. - **Troubleshooting or adding to an existing setup** (ATT, GDPR, ILRD, Test Suite, build errors on a fresh integration, or adding a feature to an already-working integration): Identify what the user needs and go directly to the relevant step or reference from "When to Read Detailed References." +- **Placement advice only** (where ads should go, which strategy fits this game): run Step 1's project check first, because the profile reads project files and an empty directory would look like a game with no loop; then Step 2 to profile the project and confirm the goal, then Step 8 for the proposal, without installing anything, because the user asked for advice, not an integration. When the proposal is approved, offer to implement it; implementation starts at Step 3, only if the user says yes, and after repeating Step 1 if the working directory has changed since. ### 1. Verify Unity Environment 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?" -### 2. Understand Business Goals +### 2. Profile the Project, then Confirm the Goal -Before implementing ad units, determine the user's optimization priorities to recommend the appropriate ad unit strategy. Ask: +Read `references/project-inference.md`, then profile the project from its files: game type, session length, key moments (each as `Class.Method()` at `file:line`), the buttons a rewarded placement needs, economy, existing monetization (each ad call found, and whether it breaks a placement guard), and target platforms. Read these rather than asking, because the files answer them and every question costs the user a turn. The one row the files cannot answer is the audience, which is asked below. Edit nothing in this step. -**"What's your primary optimization goal?"** +Show the reference's seven-row readout, starting with the legal notice from the reference's "The readout" section, word for word. Then ask two questions in one message. First the goal question with Balanced pre-filled, because with no dashboard data yet nothing justifies a heavier default: + +**"From the project this looks like a [game type] with [key moments]. I'd default to Balanced. 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. +Then the audience question, because the answer rules formats out before the goal sets numbers, and it decides the COPPA call in Step 6.5 and the `coppa` flag on any app created in Step 5: + +**"And who is the game for: a general audience, children, or both (mixed)?"** + +Record the answer in the Audience row as the user's. The agent never decides it from the project, and never states what a regulation permits or requires; when the files show a child-audience signal, name it in the question (see "Audience" in the reference). If the user does not know, record it as unanswered, propose for a general audience and say so. + +If the readout finds LevelPlay or Unity Ads already in the project, say so and offer the matching Step 0 path. If it finds an ad placement that breaks a guard (a forced ad that pays a reward, a rewarded ad with no button), say so in the readout; Step 8 proposes the conversion. If the project shows no game loop, ask the reference's three questions before the goal question, instead of guessing. Record the goal and the profile for Step 8; a correction from the user replaces that row. ### 3. Install LevelPlay SDK via UPM @@ -158,9 +167,11 @@ This configuration is required for AdMob to work as a mediation network in Level > **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](https://docs.unity.com/en-us/grow/levelplay/sdk/unity/regulation-advanced-settings) 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 the Step 2 Audience row is Child-directed or Mixed, the COPPA call below is required, from the user's own answer; say so instead of asking about COPPA again. Then, for every audience, ask the user: "LevelPlay has privacy settings for GDPR consent, CCPA, and COPPA. Which of these, if any, do you want to apply? LevelPlay's documentation describes each setting: [Regulation Advanced Settings for Unity](https://docs.unity.com/en-us/grow/levelplay/sdk/unity/regulation-advanced-settings)." When COPPA is already required from the audience answer, ask the same question about the other two settings. -**If YES to any:** +Name the settings only. Never explain what a law is, who or where it applies to, or which settings the user needs, even if asked; point to the documentation and the user's own legal counsel. Never present any option as recommended. Implement only the settings the user chooses. + +**If the user chooses any of these settings:** Privacy settings must be configured **BEFORE** SDK initialization. See `references/privacy-settings.md` for the complete implementation guide (UI, consent management, combined regulations, and the full network key list). @@ -203,7 +214,7 @@ If CCPA or COPPA fails to compile, upgrade your Unity package/SDK via **Ads Medi **For 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 `LevelPlay.Init()` — this is both an Apple platform requirement and necessary for personalized ads (which also affects fill rate). See `references/ios-setup.md` for the ATT implementation code. -**If NO privacy regulations and not targeting iOS:** Skip this step and proceed to Step 7. +**If the user applies none of these settings and isn't targeting iOS:** Skip this step and proceed to Step 7. ### 7. Initialize LevelPlay SDK @@ -255,21 +266,26 @@ LevelPlay SDK must be initialized before loading or showing any ads. Initializat The exact wiring code for each option (including the iOS coroutine placement) is in `references/initialization-api.md` (Version-Aware ILRD Init Wiring). ILRD callbacks do not fire with mock ads — a device build is needed to verify (see Step 10). For advanced options (user ID, segmentation, consent management), see `references/initialization-api.md`. -### 8. Recommend Ad Unit Strategy +### 8. Propose Placements -Based on the optimization goal identified in Step 2, recommend an ad unit strategy. +Read `references/placement-strategy.md`. Based on the optimization goal and the project profile from Step 2, propose where each ad goes in this game. If the user joined after Step 2, build the profile now first. **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 a strategy** and give a brief recommendation (full detail, benchmarks, and placement guidance are in `references/best-practices.md` under "Ad Format Strategy by Goal"): +**Map the answer to a strategy** and give a brief recommendation (full detail and frequency caps are in `references/best-practices.md` under "Ad Format Strategy by Goal"): - **Revenue-focused** → **Revenue Strategy.** Rewarded (primary monetization, multiple high-value moments) → Interstitial (secondary; at transitions; frequency cap 3–5 min) → Banner (persistent during gameplay). Bid floors are an optional revenue lever configured in Step 9. Implementation priority: **Rewarded → Interstitial → Banner**. - **UX-focused** → **UX Strategy.** Rewarded only, user-initiated (explicit opt-in), high-value rewards, **no forced ads, ever**. Interstitials optional/sparingly at session boundaries only; banners generally avoided or menu-only. Implementation priority: **Rewarded only, or Rewarded → (optional) Interstitial**. - **Balanced** → **Balanced Strategy.** Rewarded (2–3 strategic placements) → Interstitial (moderate; natural breakpoints; frequency cap 5–7 min) → Banner (selective; menus/low-attention). Implementation priority: **Rewarded → Interstitial → Banner (selective)**. - **"Not sure yet"** (from Step 2) → use the **Balanced Strategy**, then 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 still unclear, ask: "Would you prioritize revenue, user experience, or a balance of both?" +- If the Step 2 Audience row is **Child-directed** or **Mixed**, apply "Child-directed and mixed-audience games" in the reference first: banner off, rewarded off by default, no interstitial at session start, and "no ads" is a valid proposal. The goal sets numbers only inside those limits. + +**Then build the placement proposal** from the Step 2 profile and this strategy, per the reference: one table with the columns Placement | Format | Moment | Rule | Where in code, each code location a `file:line` you read, and each Moment the action that fires the ad (a press, a screen closing, a scene load), never a screen the player is still reading. An existing placement that breaks a guard is proposed as a conversion at its moment, not kept beside a new one. A rewarded placement hooks only to an existing button's press handler; a button the project lacks is named as one the user adds, never invented. No revenue, eCPM or fill figures, because the project cannot predict them. Ask: -The next step asks which ad formats to implement from this priority list. If the user wants a different order than recommended, accommodate that preference. +**"Here's where I'd put each ad in your game. Approve it as is, or tell me what to change: add, drop or move a placement, or change a cap?"** + +Apply any edit, show the changed rows, and ask again. Do not start Step 9 until the user approves the current proposal, because it decides which of their files Step 9 edits. If the user came through Step 0's advice-only path, the approved proposal is the deliverable: offer to implement it, which starts at Step 3 (repeat Step 1's project check first if the working directory has changed), and stop unless they say yes. ### 9. Implement Ad Units @@ -285,7 +301,7 @@ Verify initialization is working before proceeding with ad units." **If they answer NO or are unsure:** direct back to Step 7 and do not provide ad implementation code until initialization is confirmed working. -**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. +**Ad format checkpoint — ask before generating any code:** "Which ad formats do you want to implement? Rewarded, Interstitial, Banner, or a combination?" If the user approved a Step 8 proposal, its formats are the answer: skip this question and say "Implementing the formats from your approved proposal: [formats]." Only implement the formats the user selects. They can add more formats later using the 'Adding More Ad Formats Later' section. **First, ask the user how they want to organize the ad code. Do not generate any code until they have answered:** @@ -333,6 +349,8 @@ For each ad format, follow the implementation guidelines in the detailed referen - **Interstitial ads**: See `references/interstitial-api.md` - **Banner ads**: See `references/banner-api.md` +**Wire each approved placement** at its Step 8 code location, per "Wiring an approved placement in Step 9" in `references/placement-strategy.md`, only under organization options 1, 2 and 4, which put the agent in the user's files: list the files first, re-read each method, insert exactly one call into the ad code, and never rewrite the method. Under option 3 ("Just show me the code snippets") do not edit any gameplay script: give a call-site snippet for each approved location, named by its `file:line`, and leave the integration to the user, because that option is the user's choice to keep their files to themselves. + **Impression Level Revenue Tracking (version-aware):** See `references/ilrd-api.md` to forward impression data to the analytics platform (Firebase, AppsFlyer, Adjust, Singular, or custom backend). - **SDK 9.5.0+ (current):** subscribe to each ad object's `OnAdImpressionDataReady` event right after you create it (and unsubscribe in `OnDestroy()`). Add this to every ad manager you generate — it is the correct ILRD path in 9.5.0+. - **SDK 9.4.x and earlier:** ILRD uses the single global `LevelPlay.OnImpressionDataReady` event, wired in the init script (Step 7). If the user answered Yes/Not Sure in Step 7, it is already wired. If they said "No" and want it now, subscribe to `LevelPlay.OnImpressionDataReady` **before** the existing `LevelPlay.Init()` call. @@ -412,24 +430,27 @@ Read specific references based on what the user is doing: - **`references/dependency-resolution.md`**: Resolving native dependencies (Step 4), or gradle/CocoaPods build failures - **`references/initialization-api.md`**: Step 7 init code-organization options and ILRD init wiring; also user ID, segmentation, consent management, advanced config -- **`references/privacy-settings.md`**: GDPR, CCPA, or COPPA compliance (incl. legacy `SetConsent` and the full network key list) +- **`references/privacy-settings.md`**: the GDPR consent, CCPA, and COPPA settings (incl. legacy `SetConsent` and the full network key list) - **`references/ios-setup.md`**: iOS builds — ATT, SKAdNetwork, the iOS coroutine initializer - **`references/rewarded-api.md`** / **`references/interstitial-api.md`** / **`references/banner-api.md`**: Implementing each ad format (Step 9) -- **`references/best-practices.md`**: Strategy detail (Step 8), the Step 9 code-generation guidelines, optimization, placement +- **[`references/project-inference.md`](references/project-inference.md)**: Profiling the project from its files and the readout (Step 2) +- **[`references/placement-strategy.md`](references/placement-strategy.md)**: The placement proposal (Step 8) and wiring approved placements (Step 9) +- **`references/best-practices.md`**: Strategy detail and frequency caps (Step 8), the Step 9 code-generation guidelines, optimization - **`references/ilrd-api.md`**: Wiring ILRD to an analytics platform - **`references/testing-and-validation.md`**: Mock ads and the Test Suite (Step 10) - **`references/troubleshooting.md`**: Compile/build errors, ads not loading, callbacks not firing - **`references/migration-sdk-9.md`**: Migrating from IronSource or older LevelPlay APIs, upgrading the SDK to 9.x.x, migrating from Unity Ads, or Maven Central dependency build failures (Step 0) +- **[`references/CHANGELOG.md`](references/CHANGELOG.md)**: What changed in each version of this skill ## Examples **Note**: Examples show abbreviated workflows for illustration. In practice, follow all steps 1–10 in order. -**Revenue-focused game** ("maximize ad revenue in my casual puzzle game"): Steps 1–7 to verify environment/goal/install/deps/App Key/AdMob/init → Step 8 recommend Revenue strategy → Step 9 ask code organization and generate the chosen structure → Step 10 testing. +**Revenue-focused game** ("maximize ad revenue in my casual puzzle game"): Step 2 profiles the puzzle (level complete, hint button) and confirms Revenue → Steps 3–7 → Step 8 proposes a rewarded hint on the hint button and a capped level-complete interstitial, with `file:line` hooks → Step 9 ask code organization and wire the approved placements → Step 10 testing. -**UX-focused game** ("optional rewarded ads for extra lives without annoying players"): same spine, but Step 8 recommends UX strategy (rewarded only, user-initiated) and Step 9 implements rewarded with proper patterns. +**UX-focused game** ("optional rewarded ads for extra lives without annoying players"): same spine; the profile finds the lives system, and Step 8 proposes rewarded only, on an existing extra-life button or one the user adds. -**Existing project** ("existing GameManager, add interstitials between levels"): same spine, Step 8 Balanced, Step 9 ask to see `GameManager.cs` then provide Option-2 snippets. +**Existing project** ("existing GameManager, add interstitials between levels"): same spine; the profile cites the level-end method in `GameManager.cs`, Step 8 proposes a Balanced interstitial there, and Step 9 asks to see `GameManager.cs` then provides Option-2 snippets. ## Core Rules (reminder) @@ -438,5 +459,5 @@ These repeat the rules at the top of this file — they are the guardrails that - Base editor-side checks on the actual project rather than assumptions — read the project files, or ask the user to confirm in the Editor. The C# scripts generated in this skill are MonoBehaviour files for the user to save to their project, not for inline execution. - This skill covers the LevelPlay integration path only; it does not cover other mediation SDKs. If the user explicitly asks about alternatives, acknowledge that alternatives exist and point them to those vendors' own documentation — do not describe, characterize, or make claims about competitor products. - Follow the steps and provide only the files and configurations described in this skill. Do not proactively add steps, create files, or make recommendations based on general knowledge. If the user asks a question outside the scope of this skill, check the skill and reference files first to confirm it is not covered. If it is not, use general knowledge to respond, but do not incorporate additional steps or files into the integration workflow as a result. -- 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. +- 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. The Step 2 project profile is read from files, not asked. - When a step points to a reference file, read that reference and use its content — do not substitute general knowledge. Present the four init options (Step 7) and four organization options (Step 9) exactly as written, and ask the ILRD question (Step 7) verbatim. diff --git a/skills/using-unity/references/levelplay-unity-integration/references/CHANGELOG.md b/skills/using-unity/references/levelplay-unity-integration/references/CHANGELOG.md new file mode 100644 index 0000000..feb9351 --- /dev/null +++ b/skills/using-unity/references/levelplay-unity-integration/references/CHANGELOG.md @@ -0,0 +1,102 @@ +# Changelog + +## Contents + +- [v0.11.0 — 2026-10-08 — Project-aware placement proposals](#v0110--2026-10-08--project-aware-placement-proposals) +- [v0.10.0 — 2026-08-21 — Workflow spine, and a hard install gate](#v0100--2026-08-21--workflow-spine-and-a-hard-install-gate) +- [v0.9.0 — 2026-08-17 — SDK 9.x migration support](#v090--2026-08-17--sdk-9x-migration-support) +- [v0.8.0 — 2026-08-05 — Version-aware ILRD (SDK 9.5.0), rewarded load lifecycle, and improved activation](#v080--2026-08-05--version-aware-ilrd-sdk-950-rewarded-load-lifecycle-and-improved-activation) +- [v0.7.0 — 2026-06-12 — Initial public beta release](#v070--2026-06-12--initial-public-beta-release) + +## v0.11.0 — 2026-10-08 — Project-aware placement proposals + +The skill reads the game before it proposes ads, and proposes placements in the game's own code rather than a generic format list. + +**Added:** +- `references/project-inference.md`: how to profile the project from its files before proposing ads, in a budgeted order: game type, session length, key moments cited as `Class.Method()` at `file:line`, the buttons a rewarded placement needs, economy, existing monetization, and target platforms. The agent shows a seven-row readout, and asks at most three questions when the project has no game loop yet. +- An **Audience** row in the profile, asked with the goal question rather than inferred, because whether a game is child-directed is the developer's determination. The answer rules formats out in Step 8, makes the `SetCOPPA(true)` call in Step 6.5 required, and sets the `coppa` flag on any app created through the API. +- Existing ad placements are audited against the placement guards, not inherited: a forced ad that pays a reward, or a rewarded ad with no button, is reported as found and as needing a change, and Step 8 proposes the conversion at the same moment. +- `references/placement-strategy.md`: how to turn the profile and the optimization goal into a placement proposal (format, moment, rule, code location), with the guards that always apply. A rewarded ad is hooked only to a button the player presses, a missing button is named as one the user adds rather than invented, and the proposal carries no revenue, eCPM or fill figures. Interstitial caps follow the ranges in `best-practices.md`. +- A "Child-directed and mixed-audience games" section: banner off on every screen, rewarded off by default, no interstitial at session start, and "no ads" as a valid proposal for a free-play toy. +- The mid-action guard now covers events the game raises on its own (a timer, a year-end or wave tick, a room generating): not a transition unless the game already stops play behind a screen there. +- The proposal's Moment column names the action that fires the ad (a press, a screen closing, a scene load), never a screen the player is still reading. +- The agent never states what a regulation permits, requires or forbids; it points to `references/privacy-settings.md` for the API and leaves the determination to the developer. +- A legal notice, shown word for word before the profile table the first time the profile appears. +- Privacy settings are named, never explained: the Step 6.5 question, the Quick Reference table, the GDPR/CCPA/COPPA intros and the code samples in `references/privacy-settings.md` no longer describe what a law is or where it applies; they point to LevelPlay's Regulation Advanced Settings page, and the samples' region checks become `ShouldRequestGDPRConsent()` / `ShouldApplyCCPA()` that the developer's own logic decides. "Children" is no longer defined as under 13. +- The button search also looks for a screen's own buttons (Restart, Retry, Return, Next) in scripts, prefabs and scenes, because a lose or results screen that no script shows by name is found through the buttons on it. +- An optional `#if UNITY_EDITOR || DEVELOPMENT_BUILD` guard around the two Test Suite lines in `testing-and-validation.md`, so a forgotten removal is compiled out of release builds. Removing the lines before release is still required. + +**Changed:** +- The changelog moves to `references/CHANGELOG.md` and the README is removed, following the repository's skill layout (supplemental files live under `references/`). +- Step 2 is now "Profile the Project, then Confirm the Goal": the agent reads the project, shows the readout, then asks the existing goal question with Balanced pre-filled. +- Step 8 is now "Propose Placements": the goal-to-strategy mapping is unchanged, and it ends with a placement table the user approves or edits before Step 9. +- Step 9 skips the ad-format question when the approved proposal already answers it, and wires each approved placement with one call at its cited location. +- Evals cover the profile-then-proposal flow, the no-game-loop case, the child-directed case, an existing forced ad that pays a reward, and an automatic tick that is not an interstitial moment. + +## v0.10.0 — 2026-08-21 — Workflow spine, and a hard install gate + +Moves reference material out of the skill file and makes the SDK install a verified step rather than an assumed one. + +**Changed:** +- The skill file is now the workflow spine only, going from about 1,100 lines to 435. The dependency-resolution, testing-and-validation and troubleshooting material that was inlined in it moves into `references/`. Nothing was dropped; it is read on demand instead. The skill file is loaded in full on every invocation while a reference file is read only when a step links it, so this is a saving on every run that does not need the detail. +- The reference set grows from nine files to twelve: `dependency-resolution.md`, `testing-and-validation.md` and `troubleshooting.md` are now separate files. + +**Added:** +- **A hard install-verification gate at Step 3.** No LevelPlay code is written until `com.unity.services.levelplay` is confirmed present in `Packages/packages-lock.json`, read from the project rather than taken from the Package Manager window or an earlier turn. The package is easy to believe is installed: its display name is **Ads Mediation** while the recorded id is `com.unity.services.levelplay`, two similarly named packages are the wrong ones, and the install prompts for a second package partway through. Code written before the id resolves fails with `CS0246` on every LevelPlay symbol, which reads as a code problem rather than an install problem. The gate also distinguishes "the install never happened" from "Unity has not resolved it yet", because the fix differs. +- The deprecated-APIs section now states explicitly that `SetGDPRConsents(Dictionary)` is **not** deprecated on SDK 9.4.x, where it is the correct call, and only becomes `[Obsolete]` on 9.5.0+. It is kept out of the deprecated list rather than listed with a caveat, so it cannot be read the wrong way round. + +## v0.9.0 — 2026-08-17 — SDK 9.x migration support + +Adds guided migration to the LevelPlay 9.x SDK and the current Ad Unit (MADU) APIs. + +**New:** +- "New Integration or Migration?" routing step at the start of the workflow +- Migration reference guide covering five scenarios: SDK upgrade (.unitypackage or UPM, including switching from .unitypackage to UPM), init API migration (IronSource.Agent to LevelPlay.Init), ad unit API migration (rewarded, interstitial, banner, and the ILRD handler), Maven Central dependency build failures, and Unity Ads (Advertisement Legacy) migration +- Upgrade safety flow: Developer Settings values and installed adapters are inventoried, and the user confirms, before any folder deletion; post-upgrade steps cover adapter reinstall, settings re-entry, and removal of the stale LEVELPLAY_DEPENDENCIES_INSTALLED scripting define when switching from .unitypackage to UPM +- Migration completeness checklist covering requirements that a line-by-line translation misses: placement capping checks when dashboard placements are used, an explicit rewarded load trigger, the version API mappings, correct ILRD event names, preserved logging, HideAd vs DestroyAd intent for legacy destroyBanner calls, and removal of onApplicationPause +- Compilation check after migration edits, with errors fixed before presenting results +- Skill description now also triggers on SDK upgrades, deprecated IronSource.Agent APIs, and Unity Ads migration + +**Fixed:** +- Banner adaptive-size example used a constructor form that does not compile on any 9.x version; now configured through Config.Builder (verified against 9.0.0, 9.4.0, and 9.5.0 source) +- API mapping corrections: validateIntegration maps to LevelPlay.ValidateIntegration (not LaunchTestSuite); pluginVersion maps to LevelPlay.PluginVersion (distinct from UnityVersion); onApplicationPause is removed in 9.x with no replacement; the legacy ILRD subscription maps to LevelPlay.OnImpressionDataReady on SDK 9.4.x and earlier or per-instance OnAdImpressionDataReady on 9.5.0+ +- Unity Ads migration now surfaces that LevelPlay.Init has no test-mode parameter (Test Suite or dashboard test mode are the equivalents) instead of dropping the flag silently +- Package edits during upgrades touch only manifest.json; packages-lock.json is never hand-edited +- Maven Central migration is mentioned only when the project actually needs it +- Corrected a consent-callback name mismatch in the privacy reference, and a banner troubleshooting example that called a method banners do not have + +## v0.8.0 — 2026-08-05 — Version-aware ILRD (SDK 9.5.0), rewarded load lifecycle, and improved activation + +Accuracy and activation updates reflecting current LevelPlay SDK behavior. + +**Impression-level revenue (ILRD) — SDK 9.5.0 API change** +- ILRD now documents both delivery mechanisms: the single global `LevelPlay.OnImpressionDataReady` event (SDK 9.4.x and earlier) and the per-ad-instance `OnAdImpressionDataReady` events on each ad object (SDK 9.5.0+), which replace the global event. +- The global event still exists but is deprecated on SDK 9.5.0+ and generates a compiler warning. +- Updated the initialization step and the rewarded/interstitial/banner references to direct SDK 9.5.0+ users to the per-instance approach. + +**Rewarded ad load lifecycle** +- Clarified that `LoadAd()` must be called explicitly; the SDK does not auto-manage rewarded loading (unlike the legacy IronSource API). +- Reframed the guidance so explicit, publisher-triggered loading is the default, with eager preloading documented as an optional pattern. Applies to `references/rewarded-api.md` and the loading-strategy guidance in the skill file. + +**Description and activation** +- Reworked the skill description to increase activation on general ad and monetization requests, not only when a developer names LevelPlay. +- Added guidance at the top of the skill directing the agent to run it as an interactive, step-by-step workflow and use the reference files, rather than answering from general knowledge. + +## v0.7.0 — 2026-06-12 — Initial public beta release + +First release of the LevelPlay Unity integration skill, released as public beta. + +**Features:** +- Step-by-step installation of the LevelPlay SDK using the Ads Mediation package in Unity Package Manager +- Native dependency resolution for Android and iOS +- SDK initialization with three code organization options +- Ad unit strategy recommendations based on business goals (revenue-focused, UX-focused, or balanced) +- Implementation guides for rewarded ads, interstitials, and banner ads +- Privacy compliance support (GDPR, CCPA, COPPA) +- iOS setup (App Tracking Transparency, SKAdNetwork) +- Impression-level revenue tracking (ILRD) +- Testing guidance using mock ads and the LevelPlay Test Suite + +## Feedback + +This skill is currently in beta. [Share your feedback here](https://docs.google.com/forms/d/e/1FAIpQLSe7WvWozJ67KjgOLglSBvLug8JdgEYk895nn_BHZs0HS_bWJA/viewform). diff --git a/skills/using-unity/references/levelplay-unity-integration/references/dependency-resolution.md b/skills/using-unity/references/levelplay-unity-integration/references/dependency-resolution.md index 25041bb..76f2d21 100644 --- a/skills/using-unity/references/levelplay-unity-integration/references/dependency-resolution.md +++ b/skills/using-unity/references/levelplay-unity-integration/references/dependency-resolution.md @@ -1,6 +1,6 @@ # LevelPlay Native Dependency Resolution -Detailed guidance for Step 4 of SKILL.md. LevelPlay requires native Android/iOS libraries that Unity's +Detailed guidance for Step 4 of the workflow. LevelPlay requires native Android/iOS libraries that Unity's package manager alone doesn't handle; a dependency manager bridges this gap. Read this when resolving native dependencies, when the user does not yet have a dependency manager, or when diagnosing gradle (Android) / CocoaPods (iOS) build failures. diff --git a/skills/using-unity/references/levelplay-unity-integration/references/ilrd-api.md b/skills/using-unity/references/levelplay-unity-integration/references/ilrd-api.md index 1102b2d..9ef0cbb 100644 --- a/skills/using-unity/references/levelplay-unity-integration/references/ilrd-api.md +++ b/skills/using-unity/references/levelplay-unity-integration/references/ilrd-api.md @@ -43,7 +43,7 @@ On SDK 9.5.0+, the global `LevelPlay.OnImpressionDataReady` still exists but is ### SDK 9.5.0+ (current): Per-Instance Setup -Subscribe to `OnAdImpressionDataReady` on each ad object right after you create it — typically inside the ad manager classes from `rewarded-api.md` / `interstitial-api.md` / `banner-api.md`. There is no "before Init" ordering concern with the per-instance event; you subscribe when the ad is created. +Subscribe to `OnAdImpressionDataReady` on each ad object right after you create it — typically inside the per-format ad manager classes (the rewarded, interstitial and banner managers). There is no "before Init" ordering concern with the per-instance event; you subscribe when the ad is created. ```csharp using UnityEngine; diff --git a/skills/using-unity/references/levelplay-unity-integration/references/initialization-api.md b/skills/using-unity/references/levelplay-unity-integration/references/initialization-api.md index ea9ad74..309c1bc 100644 --- a/skills/using-unity/references/levelplay-unity-integration/references/initialization-api.md +++ b/skills/using-unity/references/levelplay-unity-integration/references/initialization-api.md @@ -1,851 +1,851 @@ -# LevelPlay SDK Initialization API - -## Contents -- [Overview](#overview) -- [Code Organization Options (Step 7)](#code-organization-options-step-7) -- [Version-Aware ILRD Init Wiring (Step 7)](#version-aware-ilrd-init-wiring-step-7) -- [Basic Initialization](#basic-initialization) -- [Advanced Initialization](#advanced-initialization) -- [API Reference](#api-reference) -- [Initialization Timing](#initialization-timing) -- [Best Practices](#best-practices) -- [Testing](#testing) -- [Migration from IronSource.* APIs](#migration-from-ironsource-apis) -- [Error Code Reference](#error-code-reference) - -## Overview - -Proper SDK initialization is critical for LevelPlay to function correctly. This reference covers basic initialization, advanced options, and best practices. - -## Code Organization Options (Step 7) - -Step 7 of SKILL.md asks the user how they want to handle initialization and presents four options. Full -implementation for each option follows. Present the four option labels exactly as written in SKILL.md; -use the code here once the user has chosen. - -### Option 1: Creating a New Script - -**If you completed ATT in Step 6.5 (iOS):** Use the `LevelPlayInitializer.cs` from `references/ios-setup.md` (Part 3) instead of the template below — it already includes the `IEnumerator Start()` coroutine required for ATT and the `DontDestroyOnLoad` setup. Skip this code block and continue from the ILRD wiring below. - -If creating a new script (e.g., `LevelPlayInitializer.cs`), use this complete class: - -```csharp -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 `Assets/Scripts/LevelPlayInitializer.cs` (or `Assets/Scripts/Ads/LevelPlayInitializer.cs` if you have an Ads subfolder) - -**After creating:** -1. Attach script to a GameObject in your first scene -2. In Unity Inspector, find the "App Key" field -3. Paste your App Key from Step 5 into that field - -### Option 2: Adding to Existing Script - -If adding to an existing script (e.g., `GameManager.cs`): - -**1. 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; -} -``` - -Replace `"YOUR_APP_KEY_HERE"` with your actual App Key from Step 5 (the alphanumeric string copied from the LevelPlay dashboard). - -**Note:** If your existing script doesn't already persist across scenes, add `DontDestroyOnLoad(gameObject);` to its `Awake()` method to prevent re-initialization when loading new scenes. - -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'. - -### Option 3: Separate Script Referenced by Manager - -If you want to keep ads code in its own script that your existing manager references: - -**1. Create `LevelPlayInitializer.cs` using the complete class code from Option 1.** - -**2. Add the `LevelPlayInitializer` component to a GameObject in the Unity Editor** (at design time — not at runtime). Use a dedicated persistent GameObject (e.g. an "Ads" object in your first scene), and set its **App Key** field in the Inspector, exactly as in Option 1's "After creating" steps. - -**3. Reference it from your existing manager** via a serialized field, so `GameManager` can coordinate with the initializer without creating it at runtime: -```csharp -using UnityEngine; - -public class GameManager : MonoBehaviour -{ - // Assign the LevelPlayInitializer GameObject in the Inspector. - // Enter your App Key on the LevelPlayInitializer component itself (see step 2), - // NOT here — that keeps your ad credentials in one place where publishers expect them. - [SerializeField] private LevelPlayInitializer levelPlayInitializer; - - void Awake() - { - // ... your other initialization code. - // LevelPlayInitializer initializes itself in its own Start(); - // GameManager just holds a reference to it via the field above. - } -} -``` - -This keeps ad code isolated in `LevelPlayInitializer.cs` while giving `GameManager` a reference to it. - -> **Why not `gameObject.AddComponent()` at runtime?** The initializer reads its App Key from a `[SerializeField]` Inspector field. A component added at runtime never receives that Inspector value, so the App Key would be empty and initialization would fail. Attaching the component in the Editor (step 2) is what makes the App Key field available to fill in. - -**Note:** `LevelPlayInitializer.Awake()` calls `DontDestroyOnLoad(gameObject)`, so the GameObject you attach it to persists across scenes. Put it on a dedicated Ads GameObject rather than on your `GameManager`, unless you intend `GameManager` to persist too. - -### Option 4: Just Show Me the Code - -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 `LevelPlayInitializer.cs`, attach it to a persistent GameObject in your first scene, and set the App Key field in the Inspector." - -**Key points (all options):** -- Always register `OnInitSuccess` and `OnInitFailed` callbacks before calling `Init()` -- Call initialization early in app lifecycle (in `Awake()` or `Start()` of first scene) -- Only initialize once. If initialization script is in first scene and you have multiple scenes, add `DontDestroyOnLoad(gameObject);` in `Awake()` to prevent re-initialization when loading new scenes -- Wait for `OnInitSuccess` before creating ad objects - -If initialization fails repeatedly, see `references/troubleshooting.md`. Common causes include incorrect App Key, no internet connection, or missing package dependencies. - -## Version-Aware ILRD Init Wiring (Step 7) - -**If the user answered Yes or Not Sure to the ILRD question in Step 7**, wire up the impression-revenue -callback. **The correct approach depends on the user's SDK version** (check in **Ads Mediation > Network -Manager**): - -**SDK 9.5.0+ (current): do NOT add anything to the initializer here.** In 9.5.0+, ILRD is delivered per -ad instance via the `OnAdImpressionDataReady` event on each ad object — it is wired when you create each -ad in Step 9 (see `references/ilrd-api.md`). The global `LevelPlay.OnImpressionDataReady` event still -exists but is **deprecated in 9.5.0+ and generates a compiler warning** — do not use it on 9.5.0+. - -**SDK 9.4.x and earlier:** subscribe to the global `LevelPlay.OnImpressionDataReady` event before -`LevelPlay.Init()`. Add these lines inside `Start()` (before `LevelPlay.Init(appKey)`): - -```csharp -// SDK 9.4.x and earlier only. 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; -``` - -**iOS path (SDK 9.4.x and earlier only):** if you used the `LevelPlayInitializer.cs` from -`references/ios-setup.md` Part 3, note that `Start()` is a coroutine with **no `LevelPlay.Init(appKey)` -call inside it** — initialization happens in `InitializeLevelPlay()`. Place the -`LevelPlay.OnImpressionDataReady += ...` line inside `InitializeLevelPlay()`, immediately **before** -`LevelPlay.Init(appKey)`, so it registers before the first impression. - -For Option 2 (existing script) and Option 3 (separate script referenced by a manager), apply the same -version-aware wiring: on 9.4.x and earlier add the global subscription/stub/unsubscribe shown above; on -9.5.0+ add nothing here (ILRD is wired per ad instance in Step 9). For Option 3, the wiring goes in -`LevelPlayInitializer.cs`, with no changes in `GameManager`. - -**Next:** Once you confirm the log fires after your first ad impression, read `references/ilrd-api.md` 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). - -## Basic Initialization - -### Minimum Required Setup - -```csharp -using UnityEngine; -using Unity.Services.LevelPlay; - -public class LevelPlayInitializer : MonoBehaviour -{ - [SerializeField] private string appKey = "YOUR_APP_KEY"; - - void Start() - { - // Register initialization callbacks - LevelPlay.OnInitSuccess += OnInitSuccess; - LevelPlay.OnInitFailed += OnInitFailed; - - // Initialize SDK - LevelPlay.Init(appKey); - } - - void OnDestroy() - { - // Unregister callbacks - LevelPlay.OnInitSuccess -= OnInitSuccess; - LevelPlay.OnInitFailed -= OnInitFailed; - } - - 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}"); - } -} -``` - -**Key points:** -- Register `OnInitSuccess` and `OnInitFailed` callbacks before calling `Init()` -- The `appKey` is obtained from your LevelPlay dashboard -- Call `Init()` as early as possible (ideally in the first scene) -- Only create ad objects after `OnInitSuccess` fires - -## Advanced Initialization - -### With User ID - -```csharp -using UnityEngine; -using Unity.Services.LevelPlay; - -public class AdvancedInitializer : MonoBehaviour -{ - [SerializeField] private string appKey = "YOUR_APP_KEY"; - - void Start() - { - // Register callbacks - LevelPlay.OnInitSuccess += OnInitSuccess; - LevelPlay.OnInitFailed += OnInitFailed; - - // Initialize SDK with optional user ID - string userId = "user_12345"; // Your internal user ID - LevelPlay.Init(appKey, userId); - } - - void OnDestroy() - { - LevelPlay.OnInitSuccess -= OnInitSuccess; - LevelPlay.OnInitFailed -= OnInitFailed; - } - - private void OnInitSuccess(LevelPlayConfiguration config) - { - Debug.Log("LevelPlay initialized successfully"); - } - - private void OnInitFailed(LevelPlayInitError error) - { - Debug.LogError($"Init failed: {error.ErrorMessage}"); - } -} -``` - -**When to use:** When you need to track users across sessions or implement server-side verification for rewards. - -### Complete Production-Ready Example - -```csharp -using UnityEngine; -using Unity.Services.LevelPlay; - -public class ProductionLevelPlayInitializer : MonoBehaviour -{ - [Header("Configuration")] - [SerializeField] private string appKey = "YOUR_APP_KEY"; - - void Awake() - { - // Ensure this object persists across scenes - DontDestroyOnLoad(gameObject); - - // Initialize as early as possible - InitializeLevelPlay(); - } - - private void InitializeLevelPlay() - { - // Register initialization callbacks - LevelPlay.OnInitSuccess += OnInitSuccess; - LevelPlay.OnInitFailed += OnInitFailed; - - // Initialize SDK with optional user ID - if (HasUserId()) - { - string userId = GetUserId(); - LevelPlay.Init(appKey, userId); - Debug.Log($"LevelPlay SDK initialization started with user ID: {userId}"); - } - else - { - LevelPlay.Init(appKey); - Debug.Log("LevelPlay SDK initialization started"); - } - } - - void OnDestroy() - { - // Unregister callbacks - LevelPlay.OnInitSuccess -= OnInitSuccess; - LevelPlay.OnInitFailed -= OnInitFailed; - } - - private void OnInitSuccess(LevelPlayConfiguration config) - { - Debug.Log("LevelPlay SDK initialization completed"); - - // SDK is ready - create ad objects here - CreateAdObjects(); - } - - private void OnInitFailed(LevelPlayInitError error) - { - Debug.LogError($"LevelPlay initialization failed: {error.ErrorMessage}"); - - // Optionally retry initialization after delay - Invoke(nameof(RetryInitialization), 5f); - } - - private void RetryInitialization() - { - Debug.Log("Retrying LevelPlay initialization..."); - LevelPlay.Init(appKey); - } - - private bool HasUserId() - { - // Check if user is logged in and has an ID - return !string.IsNullOrEmpty(PlayerPrefs.GetString("UserID", "")); - } - - private string GetUserId() - { - // Get your internal user ID - return PlayerPrefs.GetString("UserID", ""); - } - - private void CreateAdObjects() - { - // Create your ad objects here after init succeeds - // Example: - // rewardedAd = new LevelPlayRewardedAd("rewarded_ad_unit_id"); - // interstitialAd = new LevelPlayInterstitialAd("interstitial_ad_unit_id"); - Debug.Log("Creating ad objects..."); - } -} -``` - -## API Reference - -### Core Methods - -#### `LevelPlay.Init(string appKey, string userId = null)` -Initialize the LevelPlay SDK. - -**Parameters:** -- `appKey`: Your application key from LevelPlay dashboard -- `userId` (optional): Your internal user ID for tracking and server-side reward verification - -**Usage:** -```csharp -// Basic initialization -LevelPlay.Init("your_app_key"); - -// With user ID -LevelPlay.Init("your_app_key", "user_12345"); -``` - -**Important:** Register `OnInitSuccess` and `OnInitFailed` callbacks before calling `Init()`. - -**When to use user ID:** -- Server-side reward verification -- User-level analytics -- Cross-session tracking - -#### `LevelPlay.SetSegment(LevelPlaySegment segment)` -Set user segmentation data for improved ad targeting and reporting. - -**Parameters:** -- `segment`: A `LevelPlaySegment` object containing user segment information - -**Usage:** -```csharp -// Create a segment with user data -var segment = new LevelPlaySegment(); -segment.SegmentName = "high_spenders"; -segment.Level = 25; -segment.UserCreationDate = 1609459200000; // Unix timestamp in milliseconds (Jan 1, 2021) -segment.IapTotal = 49.99; -segment.IsPaying = 1; // 0 or 1 - -// Set custom parameters -segment.SetCustom("vip_tier", "gold"); -segment.SetCustom("gameplay_hours", "150"); - -// Apply segment before or after initialization -LevelPlay.SetSegment(segment); -``` - -**When to call:** -- Can be called before or after SDK initialization -- Update whenever user segment changes (level up, first purchase, etc.) -- Helps LevelPlay optimize ad delivery and reporting - -**LevelPlaySegment properties:** -- `SegmentName` (string): Name of the segment (e.g., "high_spenders", "casual_players") -- `Level` (int): User's current level in the game -- `UserCreationDate` (long): Unix timestamp of when user created their account -- `IapTotal` (double): Total amount spent on in-app purchases -- `IsPaying` (int): Whether the user has made any purchases (0 or 1) - -**LevelPlaySegment methods:** -- `SetCustom(string key, string value)`: Add custom key-value parameters for advanced segmentation - -**Custom parameter limits:** -- Maximum 5 custom parameters per segment - -**Best practices:** -- Update segments when significant user milestones occur -- Use meaningful segment names that describe user behavior -- Keep custom parameters descriptive and consistent -- Stay within the 5 custom parameter limit per segment - -#### `LevelPlay.SetPauseGame(bool pause)` -Pause Unity 3D game activities (except ad callbacks) during ad presentation. - -**Platform:** iOS only (SDK 8.5.0+) - -**Parameters:** -- `pause`: Set to `true` to pause game activities during ads - -**Usage:** -```csharp -LevelPlay.SetPauseGame(true); -``` - -**Notes:** -- iOS only -- Can be called once per session, before or after SDK initialization -- Game resumes automatically when ad closes -- Affects Rewarded and Interstitial ads - -#### `LevelPlay.SetMetaData(string key, params string[] values)` -Set metadata for SDK configuration. - -**Parameters:** -- `key`: The metadata key -- `values`: Array of values - -**Use Cases:** - -**1. Server-to-Server Rewarded Callbacks (SDK 8.11.0+)** - -Pass custom parameters for rewarded ad callbacks: - -```csharp -LevelPlay.SetMetaData("LevelPlay_Rewarded_Server_Params", new [] { "key1=value1", "key2=value2" }); -``` - -**2. Test Suite Activation** - -Enable the LevelPlay Test Suite: - -```csharp -LevelPlay.SetMetaData("is_test_suite", "enable"); -LevelPlay.Init(appKey); -``` - -**Note:** For Test Suite, must be called before `Init()`. - -#### `LevelPlay.SetDynamicUserId(string userId)` -Set a dynamic user ID that can be changed during the session for server-side rewarded ad verification. - -**Parameters:** -- `userId`: The dynamic user ID to set - -**Returns:** `bool` - true if successfully set, false otherwise - -**Usage:** -```csharp -string newUserId = "user_67890"; -bool success = LevelPlay.SetDynamicUserId(newUserId); -if (success) -{ - Debug.Log($"Dynamic user ID set to: {newUserId}"); -} -``` - -**When to use:** -- Server-side reward verification for rewarded ads -- When user ID changes mid-session (e.g., user logs in after guest play) -- Must be set before showing rewarded ads that require verification - -**Important:** This is different from the userId passed to `Init()`. The dynamic user ID can be changed during the session and is used specifically for server-to-server reward callbacks. - -#### `LevelPlay.LaunchTestSuite()` -Launch the LevelPlay Test Suite for testing ad integrations on device. - -**Usage:** -```csharp -void OnInitSuccess(LevelPlayConfiguration config) -{ - Debug.Log("SDK initialized"); - - #if UNITY_EDITOR || DEVELOPMENT_BUILD - // Launch Test Suite for testing - LevelPlay.LaunchTestSuite(); - #endif -} -``` - -**Requirements:** -- SDK must be initialized before calling this method -- Test Suite must be enabled via metadata before initialization: - ```csharp - LevelPlay.SetMetaData("is_test_suite", "enable"); - LevelPlay.Init(appKey); - ``` - -**When to use:** -- Testing ad networks on real devices -- Verifying ad fill and display for different networks -- Debugging ad integration issues -- QA testing before release - -**Notes:** -- Opens a UI overlay with test controls -- Allows testing each ad network individually -- Only available on device builds (not Editor) -- Should be removed or disabled in production builds - -#### `LevelPlay.SetAdaptersDebug(bool enabled)` -Enable or disable debug logging for ad network adapters. - -**Parameters:** -- `enabled`: Set to `true` to enable adapter debug logs, `false` to disable - -**Usage:** -```csharp -void Awake() -{ - #if UNITY_EDITOR || DEVELOPMENT_BUILD - // Enable adapter debug logs for development - LevelPlay.SetAdaptersDebug(true); - #endif - - LevelPlay.OnInitSuccess += OnInitSuccess; - LevelPlay.Init(appKey); -} -``` - -**When to use:** -- Debugging ad network integration issues -- Investigating ad load failures -- Understanding adapter behavior -- Development and QA testing - -**Notes:** -- Increases console log verbosity -- Helps diagnose network-specific issues -- Should be disabled in production builds -- Can be called before or after SDK initialization - -#### `LevelPlay.SetNetworkData(string networkKey, string networkData)` -Set custom data for specific ad networks. - -**Parameters:** -- `networkKey`: The ad network identifier (e.g., "UnityAds", "AdMob") -- `networkData`: Custom data string for the network - -**Usage:** -```csharp -// Set custom network-specific configuration -LevelPlay.SetNetworkData("UnityAds", "customValue"); -LevelPlay.SetNetworkData("AdMob", "extraConfig"); -``` - -**When to use:** -- Passing custom configuration to specific ad networks -- Advanced network-specific setup -- When network adapter requires additional data - -**Notes:** -- Call before SDK initialization -- Consult individual network adapter documentation for supported data -- Not commonly needed for standard integrations - -### Events - -#### `LevelPlay.OnInitSuccess` -Fired when SDK initialization completes successfully. - -**Signature:** `event Action` - -**Usage:** -```csharp -LevelPlay.OnInitSuccess += (config) => -{ - Debug.Log("SDK ready"); - Debug.Log($"Unity Version: {LevelPlay.UnityVersion}"); - Debug.Log($"Plugin Version: {LevelPlay.PluginVersion}"); - // Create ad objects here -}; -``` - -**Note:** `UnityVersion` and `PluginVersion` are static properties on the `LevelPlay` class, not on `LevelPlayConfiguration`. - -#### `LevelPlay.OnInitFailed` -Fired when SDK initialization fails. - -**Signature:** `event Action` - -**Usage:** -```csharp -LevelPlay.OnInitFailed += (error) => -{ - Debug.LogError($"Init failed: Code {error.ErrorCode}, Message: {error.ErrorMessage}"); - // Optionally retry -}; -``` - -**LevelPlayInitError properties:** -- `error.ErrorCode`: Numeric error code -- `error.ErrorMessage`: Description of the initialization error - -## Initialization Timing - -### Early Initialization (Recommended) - -Initialize in your first scene, as early as possible: - -```csharp -void Awake() -{ - DontDestroyOnLoad(gameObject); - - LevelPlay.OnInitSuccess += OnInitSuccess; - LevelPlay.OnInitFailed += OnInitFailed; - LevelPlay.Init(appKey); -} -``` - -**Why:** Ads start loading immediately, maximizing availability when needed. - -### Delayed Initialization (Advanced) - -In some cases, you might delay initialization: - -```csharp -void Start() -{ - // Wait for user to complete onboarding first - StartCoroutine(InitializeAfterOnboarding()); -} - -IEnumerator InitializeAfterOnboarding() -{ - yield return new WaitUntil(() => HasCompletedOnboarding()); - - // Now initialize - LevelPlay.OnInitSuccess += OnInitSuccess; - LevelPlay.OnInitFailed += OnInitFailed; - LevelPlay.Init(appKey); -} -``` - -**When to use:** -- Waiting for user consent decisions -- Completing critical onboarding first -- Reducing initial app load time - -**Trade-off:** Ads won't be ready as quickly. - -## Best Practices - -1. **Initialize early**: Call `Init()` in your first scene's `Awake()` or `Start()` -2. **Persist the initializer**: Use `DontDestroyOnLoad()` to prevent re-initialization -3. **Register callbacks first**: Always register `OnInitSuccess` and `OnInitFailed` before calling `Init()` -4. **Create ads after init**: Only create ad objects after `OnInitSuccess` fires -5. **Set user ID if available**: Helps with analytics and server-side verification -6. **Initialize only once**: Don't re-initialize the SDK across scenes -7. **Handle failures**: Implement `OnInitFailed` to catch and log initialization errors - -## Testing - -### Development Checklist -- [ ] SDK initializes successfully (check logs) -- [ ] `OnInitSuccess` callback fires -- [ ] Ads can be created after initialization -- [ ] User ID is set correctly (if used) -- [ ] Initialization happens early in app lifecycle -- [ ] Error handling works (`OnInitFailed` implemented) - -### Common Issues - -**Issue: Ads not loading after initialization** -- Check that App Key is correct -- Verify ad objects are created **after** `OnInitSuccess` fires -- Check console for initialization errors -- Enable test mode in LevelPlay dashboard - -**Issue: Initialization fails** -- Verify App Key matches LevelPlay dashboard exactly -- Check internet connectivity -- Look at `LevelPlayInitError.ErrorMessage` for specific error -- Ensure LevelPlay SDK package is properly installed - -**Issue: User ID not being tracked** -- Verify user ID is passed to `Init(appKey, userId)` as the second parameter -- Check that user ID is non-empty and unique -- Verify format meets LevelPlay requirements (alphanumeric, max 64 chars) - -**Issue: Ads not ready when needed** -- Initialize earlier in the app lifecycle -- Create ad objects immediately in `OnInitSuccess` -- Load ads immediately after creating ad objects - -## Migration from IronSource.* APIs - -> **Full migration guide:** for SDK upgrade paths, per-format ad unit API migration, the migration completeness checklist, Unity Ads migration, and Maven Central build failures, see `references/migration-sdk-9.md`. The summary below covers initialization only. - -If you're migrating from deprecated IronSource APIs: - -**Old (Deprecated):** -```csharp -IronSource.Agent.validateIntegration(); -IronSource.Agent.init(appKey); -``` - -**New (Current):** -```csharp -LevelPlay.OnInitSuccess += OnInitSuccess; -LevelPlay.OnInitFailed += OnInitFailed; -LevelPlay.Init(appKey); -``` - -**Key differences:** -- Init errors are reported via `OnInitFailed`; for integration validation use the LevelPlay Test Suite (`LaunchTestSuite()`) -- Must register callbacks before calling `Init()` -- Ad objects created explicitly after initialization (not automatic background loading) - -## Error Code Reference - -When ad operations fail, `LevelPlayAdError` contains an `ErrorCode` property with one of these values: - -> **Note:** Code **508** is an initialization/mediation-level error, surfaced via `LevelPlayInitError` in the `OnInitFailed` callback — not via a per-ad `LevelPlayAdError` (hence "N/A" in the Ad Formats column). All other codes below are per-ad errors delivered through `LevelPlayAdError` in the ad load/show failure callbacks. - -| Code | Ad Formats | Description | -|------|-----------|-------------| -| **508** | N/A | Init failure of mediation/Network, Calling Demand Only API in non Demand Only mode, Calling non Demand Only API in Demand Only mode | -| **509** | Interstitial, Rewarded | Show Fail: No ads to show | -| **510** | Interstitial, Rewarded, Banner | Load Fail: Server response failed | -| **520** | Interstitial, Rewarded | Show Fail: No internet connection; ShouldTrackNetworkState is enabled | -| **524** | Interstitial, Rewarded | Show Fail: Placement has reached its limit as defined per pace or capping limit | -| **526** | Interstitial, Rewarded | Show Fail: Ad unit has reached its daily cap per session | -| **604** | Banner | Can't load because the placement is capped | -| **605** | Banner | Unexpected exception while loading the banner | -| **606** | Banner | No banner fill on all the networks on the first load | -| **1007** | Interstitial, Rewarded | Auction Fail: Auction request did not contain all required information | -| **1022** | Rewarded | Show Fail: Cannot show a rewarded ad while another rewarded ad is showing | -| **1023** | Rewarded | Show Fail: Show called when there are no available ads to show | -| **1035** | Interstitial | Empty Waterfall | -| **1036** | Interstitial | Show Fail: Cannot show an interstitial while another interstitial is showing | -| **1037** | Interstitial | Load Fail: Cannot load an interstitial while another interstitial is loading | - -**Usage in error callbacks:** -```csharp -private void OnAdLoadFailed(LevelPlayAdError error) -{ - Debug.LogWarning($"Ad load failed: Code {error.ErrorCode}, Message: {error.ErrorMessage}"); - - // Handle specific errors - if (error.ErrorCode == 510) - { - // Server response failed - retry with backoff - } - else if (error.ErrorCode == 520) - { - // No internet connection - wait for connectivity - } -} -``` +# LevelPlay SDK Initialization API + +## Contents +- [Overview](#overview) +- [Code Organization Options (Step 7)](#code-organization-options-step-7) +- [Version-Aware ILRD Init Wiring (Step 7)](#version-aware-ilrd-init-wiring-step-7) +- [Basic Initialization](#basic-initialization) +- [Advanced Initialization](#advanced-initialization) +- [API Reference](#api-reference) +- [Initialization Timing](#initialization-timing) +- [Best Practices](#best-practices) +- [Testing](#testing) +- [Migration from IronSource.* APIs](#migration-from-ironsource-apis) +- [Error Code Reference](#error-code-reference) + +## Overview + +Proper SDK initialization is critical for LevelPlay to function correctly. This reference covers basic initialization, advanced options, and best practices. + +## Code Organization Options (Step 7) + +Step 7 of the workflow asks the user how they want to handle initialization and presents four options. Full +implementation for each option follows. Present the four option labels exactly as written in the workflow; +use the code here once the user has chosen. + +### Option 1: Creating a New Script + +**If you completed ATT in Step 6.5 (iOS):** Use the `LevelPlayInitializer.cs` from `references/ios-setup.md` (Part 3) instead of the template below — it already includes the `IEnumerator Start()` coroutine required for ATT and the `DontDestroyOnLoad` setup. Skip this code block and continue from the ILRD wiring below. + +If creating a new script (e.g., `LevelPlayInitializer.cs`), use this complete class: + +```csharp +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 `Assets/Scripts/LevelPlayInitializer.cs` (or `Assets/Scripts/Ads/LevelPlayInitializer.cs` if you have an Ads subfolder) + +**After creating:** +1. Attach script to a GameObject in your first scene +2. In Unity Inspector, find the "App Key" field +3. Paste your App Key from Step 5 into that field + +### Option 2: Adding to Existing Script + +If adding to an existing script (e.g., `GameManager.cs`): + +**1. 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; +} +``` + +Replace `"YOUR_APP_KEY_HERE"` with your actual App Key from Step 5 (the alphanumeric string copied from the LevelPlay dashboard). + +**Note:** If your existing script doesn't already persist across scenes, add `DontDestroyOnLoad(gameObject);` to its `Awake()` method to prevent re-initialization when loading new scenes. + +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'. + +### Option 3: Separate Script Referenced by Manager + +If you want to keep ads code in its own script that your existing manager references: + +**1. Create `LevelPlayInitializer.cs` using the complete class code from Option 1.** + +**2. Add the `LevelPlayInitializer` component to a GameObject in the Unity Editor** (at design time — not at runtime). Use a dedicated persistent GameObject (e.g. an "Ads" object in your first scene), and set its **App Key** field in the Inspector, exactly as in Option 1's "After creating" steps. + +**3. Reference it from your existing manager** via a serialized field, so `GameManager` can coordinate with the initializer without creating it at runtime: +```csharp +using UnityEngine; + +public class GameManager : MonoBehaviour +{ + // Assign the LevelPlayInitializer GameObject in the Inspector. + // Enter your App Key on the LevelPlayInitializer component itself (see step 2), + // NOT here — that keeps your ad credentials in one place where publishers expect them. + [SerializeField] private LevelPlayInitializer levelPlayInitializer; + + void Awake() + { + // ... your other initialization code. + // LevelPlayInitializer initializes itself in its own Start(); + // GameManager just holds a reference to it via the field above. + } +} +``` + +This keeps ad code isolated in `LevelPlayInitializer.cs` while giving `GameManager` a reference to it. + +> **Why not `gameObject.AddComponent()` at runtime?** The initializer reads its App Key from a `[SerializeField]` Inspector field. A component added at runtime never receives that Inspector value, so the App Key would be empty and initialization would fail. Attaching the component in the Editor (step 2) is what makes the App Key field available to fill in. + +**Note:** `LevelPlayInitializer.Awake()` calls `DontDestroyOnLoad(gameObject)`, so the GameObject you attach it to persists across scenes. Put it on a dedicated Ads GameObject rather than on your `GameManager`, unless you intend `GameManager` to persist too. + +### Option 4: Just Show Me the Code + +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 `LevelPlayInitializer.cs`, attach it to a persistent GameObject in your first scene, and set the App Key field in the Inspector." + +**Key points (all options):** +- Always register `OnInitSuccess` and `OnInitFailed` callbacks before calling `Init()` +- Call initialization early in app lifecycle (in `Awake()` or `Start()` of first scene) +- Only initialize once. If initialization script is in first scene and you have multiple scenes, add `DontDestroyOnLoad(gameObject);` in `Awake()` to prevent re-initialization when loading new scenes +- Wait for `OnInitSuccess` before creating ad objects + +If initialization fails repeatedly, see `references/troubleshooting.md`. Common causes include incorrect App Key, no internet connection, or missing package dependencies. + +## Version-Aware ILRD Init Wiring (Step 7) + +**If the user answered Yes or Not Sure to the ILRD question in Step 7**, wire up the impression-revenue +callback. **The correct approach depends on the user's SDK version** (check in **Ads Mediation > Network +Manager**): + +**SDK 9.5.0+ (current): do NOT add anything to the initializer here.** In 9.5.0+, ILRD is delivered per +ad instance via the `OnAdImpressionDataReady` event on each ad object — it is wired when you create each +ad in Step 9 (see `references/ilrd-api.md`). The global `LevelPlay.OnImpressionDataReady` event still +exists but is **deprecated in 9.5.0+ and generates a compiler warning** — do not use it on 9.5.0+. + +**SDK 9.4.x and earlier:** subscribe to the global `LevelPlay.OnImpressionDataReady` event before +`LevelPlay.Init()`. Add these lines inside `Start()` (before `LevelPlay.Init(appKey)`): + +```csharp +// SDK 9.4.x and earlier only. 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; +``` + +**iOS path (SDK 9.4.x and earlier only):** if you used the `LevelPlayInitializer.cs` from +`references/ios-setup.md` Part 3, note that `Start()` is a coroutine with **no `LevelPlay.Init(appKey)` +call inside it** — initialization happens in `InitializeLevelPlay()`. Place the +`LevelPlay.OnImpressionDataReady += ...` line inside `InitializeLevelPlay()`, immediately **before** +`LevelPlay.Init(appKey)`, so it registers before the first impression. + +For Option 2 (existing script) and Option 3 (separate script referenced by a manager), apply the same +version-aware wiring: on 9.4.x and earlier add the global subscription/stub/unsubscribe shown above; on +9.5.0+ add nothing here (ILRD is wired per ad instance in Step 9). For Option 3, the wiring goes in +`LevelPlayInitializer.cs`, with no changes in `GameManager`. + +**Next:** Once you confirm the log fires after your first ad impression, read `references/ilrd-api.md` 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). + +## Basic Initialization + +### Minimum Required Setup + +```csharp +using UnityEngine; +using Unity.Services.LevelPlay; + +public class LevelPlayInitializer : MonoBehaviour +{ + [SerializeField] private string appKey = "YOUR_APP_KEY"; + + void Start() + { + // Register initialization callbacks + LevelPlay.OnInitSuccess += OnInitSuccess; + LevelPlay.OnInitFailed += OnInitFailed; + + // Initialize SDK + LevelPlay.Init(appKey); + } + + void OnDestroy() + { + // Unregister callbacks + LevelPlay.OnInitSuccess -= OnInitSuccess; + LevelPlay.OnInitFailed -= OnInitFailed; + } + + 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}"); + } +} +``` + +**Key points:** +- Register `OnInitSuccess` and `OnInitFailed` callbacks before calling `Init()` +- The `appKey` is obtained from your LevelPlay dashboard +- Call `Init()` as early as possible (ideally in the first scene) +- Only create ad objects after `OnInitSuccess` fires + +## Advanced Initialization + +### With User ID + +```csharp +using UnityEngine; +using Unity.Services.LevelPlay; + +public class AdvancedInitializer : MonoBehaviour +{ + [SerializeField] private string appKey = "YOUR_APP_KEY"; + + void Start() + { + // Register callbacks + LevelPlay.OnInitSuccess += OnInitSuccess; + LevelPlay.OnInitFailed += OnInitFailed; + + // Initialize SDK with optional user ID + string userId = "user_12345"; // Your internal user ID + LevelPlay.Init(appKey, userId); + } + + void OnDestroy() + { + LevelPlay.OnInitSuccess -= OnInitSuccess; + LevelPlay.OnInitFailed -= OnInitFailed; + } + + private void OnInitSuccess(LevelPlayConfiguration config) + { + Debug.Log("LevelPlay initialized successfully"); + } + + private void OnInitFailed(LevelPlayInitError error) + { + Debug.LogError($"Init failed: {error.ErrorMessage}"); + } +} +``` + +**When to use:** When you need to track users across sessions or implement server-side verification for rewards. + +### Complete Production-Ready Example + +```csharp +using UnityEngine; +using Unity.Services.LevelPlay; + +public class ProductionLevelPlayInitializer : MonoBehaviour +{ + [Header("Configuration")] + [SerializeField] private string appKey = "YOUR_APP_KEY"; + + void Awake() + { + // Ensure this object persists across scenes + DontDestroyOnLoad(gameObject); + + // Initialize as early as possible + InitializeLevelPlay(); + } + + private void InitializeLevelPlay() + { + // Register initialization callbacks + LevelPlay.OnInitSuccess += OnInitSuccess; + LevelPlay.OnInitFailed += OnInitFailed; + + // Initialize SDK with optional user ID + if (HasUserId()) + { + string userId = GetUserId(); + LevelPlay.Init(appKey, userId); + Debug.Log($"LevelPlay SDK initialization started with user ID: {userId}"); + } + else + { + LevelPlay.Init(appKey); + Debug.Log("LevelPlay SDK initialization started"); + } + } + + void OnDestroy() + { + // Unregister callbacks + LevelPlay.OnInitSuccess -= OnInitSuccess; + LevelPlay.OnInitFailed -= OnInitFailed; + } + + private void OnInitSuccess(LevelPlayConfiguration config) + { + Debug.Log("LevelPlay SDK initialization completed"); + + // SDK is ready - create ad objects here + CreateAdObjects(); + } + + private void OnInitFailed(LevelPlayInitError error) + { + Debug.LogError($"LevelPlay initialization failed: {error.ErrorMessage}"); + + // Optionally retry initialization after delay + Invoke(nameof(RetryInitialization), 5f); + } + + private void RetryInitialization() + { + Debug.Log("Retrying LevelPlay initialization..."); + LevelPlay.Init(appKey); + } + + private bool HasUserId() + { + // Check if user is logged in and has an ID + return !string.IsNullOrEmpty(PlayerPrefs.GetString("UserID", "")); + } + + private string GetUserId() + { + // Get your internal user ID + return PlayerPrefs.GetString("UserID", ""); + } + + private void CreateAdObjects() + { + // Create your ad objects here after init succeeds + // Example: + // rewardedAd = new LevelPlayRewardedAd("rewarded_ad_unit_id"); + // interstitialAd = new LevelPlayInterstitialAd("interstitial_ad_unit_id"); + Debug.Log("Creating ad objects..."); + } +} +``` + +## API Reference + +### Core Methods + +#### `LevelPlay.Init(string appKey, string userId = null)` +Initialize the LevelPlay SDK. + +**Parameters:** +- `appKey`: Your application key from LevelPlay dashboard +- `userId` (optional): Your internal user ID for tracking and server-side reward verification + +**Usage:** +```csharp +// Basic initialization +LevelPlay.Init("your_app_key"); + +// With user ID +LevelPlay.Init("your_app_key", "user_12345"); +``` + +**Important:** Register `OnInitSuccess` and `OnInitFailed` callbacks before calling `Init()`. + +**When to use user ID:** +- Server-side reward verification +- User-level analytics +- Cross-session tracking + +#### `LevelPlay.SetSegment(LevelPlaySegment segment)` +Set user segmentation data for improved ad targeting and reporting. + +**Parameters:** +- `segment`: A `LevelPlaySegment` object containing user segment information + +**Usage:** +```csharp +// Create a segment with user data +var segment = new LevelPlaySegment(); +segment.SegmentName = "high_spenders"; +segment.Level = 25; +segment.UserCreationDate = 1609459200000; // Unix timestamp in milliseconds (Jan 1, 2021) +segment.IapTotal = 49.99; +segment.IsPaying = 1; // 0 or 1 + +// Set custom parameters +segment.SetCustom("vip_tier", "gold"); +segment.SetCustom("gameplay_hours", "150"); + +// Apply segment before or after initialization +LevelPlay.SetSegment(segment); +``` + +**When to call:** +- Can be called before or after SDK initialization +- Update whenever user segment changes (level up, first purchase, etc.) +- Helps LevelPlay optimize ad delivery and reporting + +**LevelPlaySegment properties:** +- `SegmentName` (string): Name of the segment (e.g., "high_spenders", "casual_players") +- `Level` (int): User's current level in the game +- `UserCreationDate` (long): Unix timestamp of when user created their account +- `IapTotal` (double): Total amount spent on in-app purchases +- `IsPaying` (int): Whether the user has made any purchases (0 or 1) + +**LevelPlaySegment methods:** +- `SetCustom(string key, string value)`: Add custom key-value parameters for advanced segmentation + +**Custom parameter limits:** +- Maximum 5 custom parameters per segment + +**Best practices:** +- Update segments when significant user milestones occur +- Use meaningful segment names that describe user behavior +- Keep custom parameters descriptive and consistent +- Stay within the 5 custom parameter limit per segment + +#### `LevelPlay.SetPauseGame(bool pause)` +Pause Unity 3D game activities (except ad callbacks) during ad presentation. + +**Platform:** iOS only (SDK 8.5.0+) + +**Parameters:** +- `pause`: Set to `true` to pause game activities during ads + +**Usage:** +```csharp +LevelPlay.SetPauseGame(true); +``` + +**Notes:** +- iOS only +- Can be called once per session, before or after SDK initialization +- Game resumes automatically when ad closes +- Affects Rewarded and Interstitial ads + +#### `LevelPlay.SetMetaData(string key, params string[] values)` +Set metadata for SDK configuration. + +**Parameters:** +- `key`: The metadata key +- `values`: Array of values + +**Use Cases:** + +**1. Server-to-Server Rewarded Callbacks (SDK 8.11.0+)** + +Pass custom parameters for rewarded ad callbacks: + +```csharp +LevelPlay.SetMetaData("LevelPlay_Rewarded_Server_Params", new [] { "key1=value1", "key2=value2" }); +``` + +**2. Test Suite Activation** + +Enable the LevelPlay Test Suite: + +```csharp +LevelPlay.SetMetaData("is_test_suite", "enable"); +LevelPlay.Init(appKey); +``` + +**Note:** For Test Suite, must be called before `Init()`. + +#### `LevelPlay.SetDynamicUserId(string userId)` +Set a dynamic user ID that can be changed during the session for server-side rewarded ad verification. + +**Parameters:** +- `userId`: The dynamic user ID to set + +**Returns:** `bool` - true if successfully set, false otherwise + +**Usage:** +```csharp +string newUserId = "user_67890"; +bool success = LevelPlay.SetDynamicUserId(newUserId); +if (success) +{ + Debug.Log($"Dynamic user ID set to: {newUserId}"); +} +``` + +**When to use:** +- Server-side reward verification for rewarded ads +- When user ID changes mid-session (e.g., user logs in after guest play) +- Must be set before showing rewarded ads that require verification + +**Important:** This is different from the userId passed to `Init()`. The dynamic user ID can be changed during the session and is used specifically for server-to-server reward callbacks. + +#### `LevelPlay.LaunchTestSuite()` +Launch the LevelPlay Test Suite for testing ad integrations on device. + +**Usage:** +```csharp +void OnInitSuccess(LevelPlayConfiguration config) +{ + Debug.Log("SDK initialized"); + + #if UNITY_EDITOR || DEVELOPMENT_BUILD + // Launch Test Suite for testing + LevelPlay.LaunchTestSuite(); + #endif +} +``` + +**Requirements:** +- SDK must be initialized before calling this method +- Test Suite must be enabled via metadata before initialization: + ```csharp + LevelPlay.SetMetaData("is_test_suite", "enable"); + LevelPlay.Init(appKey); + ``` + +**When to use:** +- Testing ad networks on real devices +- Verifying ad fill and display for different networks +- Debugging ad integration issues +- QA testing before release + +**Notes:** +- Opens a UI overlay with test controls +- Allows testing each ad network individually +- Only available on device builds (not Editor) +- Should be removed or disabled in production builds + +#### `LevelPlay.SetAdaptersDebug(bool enabled)` +Enable or disable debug logging for ad network adapters. + +**Parameters:** +- `enabled`: Set to `true` to enable adapter debug logs, `false` to disable + +**Usage:** +```csharp +void Awake() +{ + #if UNITY_EDITOR || DEVELOPMENT_BUILD + // Enable adapter debug logs for development + LevelPlay.SetAdaptersDebug(true); + #endif + + LevelPlay.OnInitSuccess += OnInitSuccess; + LevelPlay.Init(appKey); +} +``` + +**When to use:** +- Debugging ad network integration issues +- Investigating ad load failures +- Understanding adapter behavior +- Development and QA testing + +**Notes:** +- Increases console log verbosity +- Helps diagnose network-specific issues +- Should be disabled in production builds +- Can be called before or after SDK initialization + +#### `LevelPlay.SetNetworkData(string networkKey, string networkData)` +Set custom data for specific ad networks. + +**Parameters:** +- `networkKey`: The ad network identifier (e.g., "UnityAds", "AdMob") +- `networkData`: Custom data string for the network + +**Usage:** +```csharp +// Set custom network-specific configuration +LevelPlay.SetNetworkData("UnityAds", "customValue"); +LevelPlay.SetNetworkData("AdMob", "extraConfig"); +``` + +**When to use:** +- Passing custom configuration to specific ad networks +- Advanced network-specific setup +- When network adapter requires additional data + +**Notes:** +- Call before SDK initialization +- Consult individual network adapter documentation for supported data +- Not commonly needed for standard integrations + +### Events + +#### `LevelPlay.OnInitSuccess` +Fired when SDK initialization completes successfully. + +**Signature:** `event Action` + +**Usage:** +```csharp +LevelPlay.OnInitSuccess += (config) => +{ + Debug.Log("SDK ready"); + Debug.Log($"Unity Version: {LevelPlay.UnityVersion}"); + Debug.Log($"Plugin Version: {LevelPlay.PluginVersion}"); + // Create ad objects here +}; +``` + +**Note:** `UnityVersion` and `PluginVersion` are static properties on the `LevelPlay` class, not on `LevelPlayConfiguration`. + +#### `LevelPlay.OnInitFailed` +Fired when SDK initialization fails. + +**Signature:** `event Action` + +**Usage:** +```csharp +LevelPlay.OnInitFailed += (error) => +{ + Debug.LogError($"Init failed: Code {error.ErrorCode}, Message: {error.ErrorMessage}"); + // Optionally retry +}; +``` + +**LevelPlayInitError properties:** +- `error.ErrorCode`: Numeric error code +- `error.ErrorMessage`: Description of the initialization error + +## Initialization Timing + +### Early Initialization (Recommended) + +Initialize in your first scene, as early as possible: + +```csharp +void Awake() +{ + DontDestroyOnLoad(gameObject); + + LevelPlay.OnInitSuccess += OnInitSuccess; + LevelPlay.OnInitFailed += OnInitFailed; + LevelPlay.Init(appKey); +} +``` + +**Why:** Ads start loading immediately, maximizing availability when needed. + +### Delayed Initialization (Advanced) + +In some cases, you might delay initialization: + +```csharp +void Start() +{ + // Wait for user to complete onboarding first + StartCoroutine(InitializeAfterOnboarding()); +} + +IEnumerator InitializeAfterOnboarding() +{ + yield return new WaitUntil(() => HasCompletedOnboarding()); + + // Now initialize + LevelPlay.OnInitSuccess += OnInitSuccess; + LevelPlay.OnInitFailed += OnInitFailed; + LevelPlay.Init(appKey); +} +``` + +**When to use:** +- Waiting for user consent decisions +- Completing critical onboarding first +- Reducing initial app load time + +**Trade-off:** Ads won't be ready as quickly. + +## Best Practices + +1. **Initialize early**: Call `Init()` in your first scene's `Awake()` or `Start()` +2. **Persist the initializer**: Use `DontDestroyOnLoad()` to prevent re-initialization +3. **Register callbacks first**: Always register `OnInitSuccess` and `OnInitFailed` before calling `Init()` +4. **Create ads after init**: Only create ad objects after `OnInitSuccess` fires +5. **Set user ID if available**: Helps with analytics and server-side verification +6. **Initialize only once**: Don't re-initialize the SDK across scenes +7. **Handle failures**: Implement `OnInitFailed` to catch and log initialization errors + +## Testing + +### Development Checklist +- [ ] SDK initializes successfully (check logs) +- [ ] `OnInitSuccess` callback fires +- [ ] Ads can be created after initialization +- [ ] User ID is set correctly (if used) +- [ ] Initialization happens early in app lifecycle +- [ ] Error handling works (`OnInitFailed` implemented) + +### Common Issues + +**Issue: Ads not loading after initialization** +- Check that App Key is correct +- Verify ad objects are created **after** `OnInitSuccess` fires +- Check console for initialization errors +- Enable test mode in LevelPlay dashboard + +**Issue: Initialization fails** +- Verify App Key matches LevelPlay dashboard exactly +- Check internet connectivity +- Look at `LevelPlayInitError.ErrorMessage` for specific error +- Ensure LevelPlay SDK package is properly installed + +**Issue: User ID not being tracked** +- Verify user ID is passed to `Init(appKey, userId)` as the second parameter +- Check that user ID is non-empty and unique +- Verify format meets LevelPlay requirements (alphanumeric, max 64 chars) + +**Issue: Ads not ready when needed** +- Initialize earlier in the app lifecycle +- Create ad objects immediately in `OnInitSuccess` +- Load ads immediately after creating ad objects + +## Migration from IronSource.* APIs + +> **Full migration guide:** for SDK upgrade paths, per-format ad unit API migration, the migration completeness checklist, Unity Ads migration, and Maven Central build failures, see `references/migration-sdk-9.md`. The summary below covers initialization only. + +If you're migrating from deprecated IronSource APIs: + +**Old (Deprecated):** +```csharp +IronSource.Agent.validateIntegration(); +IronSource.Agent.init(appKey); +``` + +**New (Current):** +```csharp +LevelPlay.OnInitSuccess += OnInitSuccess; +LevelPlay.OnInitFailed += OnInitFailed; +LevelPlay.Init(appKey); +``` + +**Key differences:** +- Init errors are reported via `OnInitFailed`; for integration validation use the LevelPlay Test Suite (`LaunchTestSuite()`) +- Must register callbacks before calling `Init()` +- Ad objects created explicitly after initialization (not automatic background loading) + +## Error Code Reference + +When ad operations fail, `LevelPlayAdError` contains an `ErrorCode` property with one of these values: + +> **Note:** Code **508** is an initialization/mediation-level error, surfaced via `LevelPlayInitError` in the `OnInitFailed` callback — not via a per-ad `LevelPlayAdError` (hence "N/A" in the Ad Formats column). All other codes below are per-ad errors delivered through `LevelPlayAdError` in the ad load/show failure callbacks. + +| Code | Ad Formats | Description | +|------|-----------|-------------| +| **508** | N/A | Init failure of mediation/Network, Calling Demand Only API in non Demand Only mode, Calling non Demand Only API in Demand Only mode | +| **509** | Interstitial, Rewarded | Show Fail: No ads to show | +| **510** | Interstitial, Rewarded, Banner | Load Fail: Server response failed | +| **520** | Interstitial, Rewarded | Show Fail: No internet connection; ShouldTrackNetworkState is enabled | +| **524** | Interstitial, Rewarded | Show Fail: Placement has reached its limit as defined per pace or capping limit | +| **526** | Interstitial, Rewarded | Show Fail: Ad unit has reached its daily cap per session | +| **604** | Banner | Can't load because the placement is capped | +| **605** | Banner | Unexpected exception while loading the banner | +| **606** | Banner | No banner fill on all the networks on the first load | +| **1007** | Interstitial, Rewarded | Auction Fail: Auction request did not contain all required information | +| **1022** | Rewarded | Show Fail: Cannot show a rewarded ad while another rewarded ad is showing | +| **1023** | Rewarded | Show Fail: Show called when there are no available ads to show | +| **1035** | Interstitial | Empty Waterfall | +| **1036** | Interstitial | Show Fail: Cannot show an interstitial while another interstitial is showing | +| **1037** | Interstitial | Load Fail: Cannot load an interstitial while another interstitial is loading | + +**Usage in error callbacks:** +```csharp +private void OnAdLoadFailed(LevelPlayAdError error) +{ + Debug.LogWarning($"Ad load failed: Code {error.ErrorCode}, Message: {error.ErrorMessage}"); + + // Handle specific errors + if (error.ErrorCode == 510) + { + // Server response failed - retry with backoff + } + else if (error.ErrorCode == 520) + { + // No internet connection - wait for connectivity + } +} +``` diff --git a/skills/using-unity/references/levelplay-unity-integration/references/placement-strategy.md b/skills/using-unity/references/levelplay-unity-integration/references/placement-strategy.md new file mode 100644 index 0000000..dae53ab --- /dev/null +++ b/skills/using-unity/references/levelplay-unity-integration/references/placement-strategy.md @@ -0,0 +1,413 @@ +# Placement Strategy: From Project Profile to Ad Placements + +How to turn the Step 2 project profile and the user's optimization goal into concrete placements +that Step 8 proposes and Step 9 implements. Every placement is a **format, a moment, a rule and a +location in the code**, because that is what becomes real code, while "use rewarded ads" does not. + +## Contents + +- [How to use this reference](#how-to-use-this-reference) +- [A proposal, not a promise](#a-proposal-not-a-promise) +- [Anchor placements to the project's code](#anchor-placements-to-the-projects-code) +- [Genre to format mapping](#genre-to-format-mapping) +- [Rule templates](#rule-templates) +- [Guards that always apply](#guards-that-always-apply) +- [Child-directed and mixed-audience games](#child-directed-and-mixed-audience-games) +- [Naming the placements](#naming-the-placements) +- [Where each placement goes](#where-each-placement-goes) +- [A placement that needs UI the project lacks](#a-placement-that-needs-ui-the-project-lacks) +- [The reward on a rewarded placement](#the-reward-on-a-rewarded-placement) +- [Banner: usually off, and how to say so](#banner-usually-off-and-how-to-say-so) +- [Shifting the balance with the user's goal](#shifting-the-balance-with-the-users-goal) +- [Bid floors stay optional](#bid-floors-stay-optional) +- [The proposal table](#the-proposal-table) +- [Wiring an approved placement in Step 9](#wiring-an-approved-placement-in-step-9) +- [Adding a format later](#adding-a-format-later) +- [Worked examples](#worked-examples) + +## How to use this reference + +1. Take the profile rows from Step 2: game type, session length, key moments (each with its + `Class.Method` and `file:line`), the buttons found or missing, the economy, any existing ad + placement and whether it breaks a guard, and the audience answer. +2. **Start from the key moments found.** Each one that maps to a format becomes a placement, + anchored to its method, per [Anchor placements to the project's code](#anchor-placements-to-the-projects-code). +3. Fill gaps from [Genre to format mapping](#genre-to-format-mapping): only formats the found + moments did not already cover, and only where the genre calls for them. +4. Fill each format's [rule template](#rule-templates) with the game's own values: the real run + length, the real death moment, the real currency name. +5. Apply every [guard that always applies](#guards-that-always-apply), and the + [child-directed rules](#child-directed-and-mixed-audience-games) when the audience row says so. +6. Set the numbers from the user's goal, per [Shifting the balance](#shifting-the-balance-with-the-users-goal). +7. Present [the proposal table](#the-proposal-table) and ask the user to approve or edit it. + +Present one proposal derived from this game, not a menu of strategies, because the user's edits are +a faster way to the right plan than choosing between abstract options. + +## A proposal, not a promise + +The user decides on the proposal: approve, edit, or decline. Word it that way: what each placement +is, when it fires, and what protects the player. **Never promise or imply an outcome**: no +"maximize" or "boost revenue", no earnings, eCPM or fill figure, and none of the industry benchmark +percentages from `best-practices.md`. What a placement earns depends on the players, the market and +the demand, none of which the project files show; the LevelPlay dashboard reports it once the game +is live. Explain fit, not income. + +The same holds for the law. Never state what a regulation permits, requires or forbids ("under +COPPA only contextual ads are allowed"): the skill says which API to call for a setting the user +has decided on (`references/privacy-settings.md`), and the developer decides the setting with their +own counsel. Point there; do not paraphrase the regulation. + +## Anchor placements to the project's code + +A placement tied to the game's code ("an interstitial in `RunManager.ReturnToMenu()`") is one the +user can picture, check and correct. A generic trigger is one they have to wire themselves. So: + +- **Derive placements from the found moments first.** A death offers the rewarded revive, a level + complete takes the interstitial, the return to menu takes the between-runs interstitial. Genre + defaults fill only what the found moments leave uncovered. +- **The hook depends on the format.** An interstitial is hooked to the **moment** itself: the method + where the level completes or the run returns to the menu. A rewarded ad is hooked **only to the + handler of the button the player presses** to accept it (the Revive button, the Double coins + button), never to the moment that makes the offer appear (`PlayerHealth.Die()`, + `ResultsPanel.Show()`), because a call there plays a rewarded ad nobody chose to watch. +- **Copy the location from the profile.** The `Class.Method` and `file:line` come from a method + Step 2 read. Never invent or tidy a symbol, and never point at a file you have not read. +- **A banner belongs to a screen, not a method.** Name the screen; its show and hide calls go where + that screen opens and closes. +- **No matching method found** means the placement has no code location, and the proposal says so + in words ("no return-to-menu method found: you call it where a run ends"). Never fill the gap with + a plausible method name. + +## Genre to format mapping + +Pick the closest row. A game that straddles two rows takes the more conservative of the two. + +| Game type | Primary | Secondary | Banner | Why | +|---|---|---|---|---| +| Endless runner, arcade score-attack | Rewarded revive | Interstitial between runs | Off | Death is a high-intent moment; runs are short, so the between-runs break needs a cap | +| Level-based puzzle | Rewarded hint or extra moves | Interstitial on level complete | Menu only | Failure is a stuck state, not a death; a hint is a natural opt-in | +| Idle, incremental | Rewarded multiplier or offline-earnings boost | Interstitial rarely, if at all | Main idle screen acceptable | Long idle screens tolerate a banner; the economy gives a multiplier something to multiply | +| Casual sim, tycoon, builder | Rewarded currency or speed-up | Interstitial at a session boundary | Menu only | Progression gates create natural rewarded demand | +| Action, shooter, platformer with lives | Rewarded continue | Interstitial on game over | Off | Interrupting action breaks the play the player came for | +| Narrative, story, puzzle-adventure | Rewarded hint only | None | Off | Interruption breaks the story | +| Card, board, casual multiplayer | Rewarded bonus or second chance | Interstitial between matches | Off | Match boundaries are clean breaks | +| Unclear or prototype | Rewarded only | None | Off | With no established loop, one opt-in format is the honest proposal | + +When Step 2 found no key moments, use the last row whatever the genre, and say that more placements +can be added once the loop exists. + +## Rule templates + +Fill each template with the game's own values. Bracketed parts change per game. + +**Rewarded revive or continue** + +- Moment: the player dies or fails, at the death or fail method from the profile. +- Hook: the Revive or Continue button's press handler. +- Rule: one per run. +- Reward: 1 `[Revive]`. + +**Rewarded currency, hint or multiplier** + +- Moment: the player is short of `[currency]` at a purchase point, asks for a hint, or sees the + results screen. +- Hook: the button's press handler. +- Rule: a daily ceiling (for example 3 to 5), so the reward keeps its value. +- Reward: `[amount] [currency]`, 1 Hint, or 1 `[multiplier]`. + +**Interstitial between runs or levels** + +- Moment: the run or level ends and the player returns to `[the menu or next-level screen]`. +- Hook: that method, before the scene load or screen change. +- Rule: from run `[N]` onward, at most one every `[M]` minutes, and never right after a rewarded ad. + +Choose `N` from session length, because short runs reach a break more often: + +| Session shape | Start at | +|---|---| +| Runs under 1 minute | Run 4 | +| Runs of 1 to 3 minutes | Run 3 | +| Sessions longer than 3 minutes, or no run unit | The second session boundary | + +Choose `M` from the user's goal, using the ranges in `best-practices.md` ("Frequency Management"), +because those are the skill's single source for frequency caps: **Balanced 5 to 7 minutes**, +**Revenue-focused 3 to 5 minutes**, **UX-focused session boundaries only** (once per session, or 10+ +minutes). Start in the middle of the range and say the user can tune it once dashboard data exists. + +**Banner** + +- Moment: a named non-gameplay screen. +- Rule: shown while that screen is open, hidden when it closes, never over an interactive element. + +## Guards that always apply + +These hold in every proposal and every goal, because they protect players from outcomes the user +has not seen yet. A goal changes the numbers, never these: + +- **Rewarded only from a press.** A rewarded ad plays only from an explicit button-press handler the + player chose. Never from a death, a screen show, a timer or a scene load. +- **Interstitial at the moment, never mid-action.** A forced ad fires at the transition itself (level + complete, return to menu), never while the player has control, and never while the player has + paused the game. An event the game raises on its own, with no press from the player (a timer, a + year-end or wave tick in a running simulation, a new room generating as the player walks in) is + not a transition unless the game already stops play behind a screen at that event; otherwise it + fires during play, and no interstitial goes there. +- **Protect the first runs, from forced ads only.** No interstitial before run `N`, and never on the + first run of a first session, because a new player who meets an ad before they understand the + game is the most likely to leave. Rewarded offers are available from the first run, because the + player can decline them. +- **Never stack.** An interstitial never directly follows a rewarded ad, in either order. +- **Failure is silent.** If an ad is not ready or fails, gameplay continues as if it was never + offered: no error dialog, no blocked progression, and a rewarded flow returns the player to where + they were. See "Error Handling and Graceful Degradation" in `best-practices.md`. +- **No ad before initialization.** Create and load ads only after `LevelPlay.Init()` has been + called — on device from `OnInitSuccess`; in the Editor, where that callback may not fire, creating + them in `Start()` after `Init()` is the documented mock-ad path (see the initialization note in + `testing-and-validation.md`) — and show only when the ad reports it is ready, because an ad created + before `Init()` never loads. + +## Child-directed and mixed-audience games + +When the Step 2 audience row is `Child-directed` or `Mixed`, apply these before the goal sets any +number, and treat both answers the same, because a mixed-audience game is played by children too. +The user can relax a rule on the proposal; the agent does not relax one for them: + +- **Banner off, on every screen.** A banner beside the play area or on a home screen invites + accidental taps from small fingers, so it is off whatever the goal, and the proposal says why in + one clause. +- **Rewarded off by default.** A rewarded offer is a value exchange ("watch this, get that") that a + young child cannot weigh, so propose none. If the game has a screen a parent reaches (settings, a + shop behind a gate), one rewarded offer may be proposed there, named as such. +- **Interstitial only at a break the player chose, never at session start.** The press that starts + play is the first thing a child does, so no forced ad goes there, nor on a return to the home + screen that a child reaches by stopping. A level complete in a game with levels qualifies, at most + once per session, from the second session. +- **"No ads" is a valid proposal.** A free-play toy with no break and no economy (a soundboard, a + toddler sandbox) has no placement that passes these rules, so the proposal says so in one line + and stops. Nothing is invented so that there is something to propose. +- **The setting is the user's, the law is not the agent's to state.** `SetCOPPA(true)` before + `LevelPlay.Init()` in Step 6.5, and `coppa: 1` on the app in Step 5, both follow from the user's + answer; say that they do. What any regulation allows is not for the agent to say, per "A + proposal, not a promise" above. + +## Naming the placements + +Give each placement one human-readable name and use it everywhere it appears: the proposal table, +code comments, and the ad unit the user creates in the LevelPlay dashboard. One name lets the user +follow one moment of their game from the proposal to the dashboard. + +Real words, first word capitalised, 24 characters or fewer, naming the **moment**, not the format: + +| Placement | Name | +|---|---| +| Rewarded revive offered at death | Revive after death | +| Rewarded hint on the hint button | Free hint | +| Rewarded 2x offline earnings | Offline earnings boost | +| Interstitial on return to menu after a run | Between runs | +| Interstitial on level complete | Level complete | +| Banner on the main menu | Main menu banner | + +Never `Rewarded_Revive` or `DefaultRewardedVideo`: the format is already in its own column, and an +identifier says nothing about where the ad runs. If the user also uses LevelPlay dashboard +placements (the `placementName` passed to `ShowAd`), derive that name from the same one, for +example `between_runs`. + +## Where each placement goes + +Every placement answers two questions, because the user is agreeing to something that will appear +on their screens and in their code: + +- **On screen**: the screen and position in the player's terms ("Death screen, before results", + "Main menu, bottom", "Hint button, level screen"). +- **In code**: `Class.Method()` at `file:line`, when a method was read. Otherwise say who adds the + call. + +**A project with no gameplay code to hook** (a template, an empty scene, a prototype with no loop) +gets on-screen positions only, and the proposal says so: "These are recommended positions to wire +once the game has a results screen and a death moment." Never present a recommended position as a +moment the project already has. + +## A placement that needs UI the project lacks + +A rewarded offer is always a press, so its button is part of the placement. Check whether the +button exists before saying it does, per "UI a placement needs" in `project-inference.md`. + +- **Found**: hook the placement to the button's handler and name it in the proposal. +- **Not found**: still propose the placement, and say what is missing: "Double coins on the results + screen: **needs a Double coins button on the results screen**. You add the button; Step 9 writes + the ad call for its handler." + - The on-screen position must not imply the button exists: "Results screen, button to add", never + "Double coins button". + - No code location, and never the method that shows the screen as a stand-in, because that would + play a rewarded ad nobody pressed for. + - Step 9 writes the ad-side method (show, cap, reward callback) and tells the user where to call + it. Do not create, generate or lay out the button, because building the game's UI is outside + this skill and an invented button would not match their screens. + +## The reward on a rewarded placement + +Every rewarded placement states its reward in the proposal, in the game's own word: `1 Revive`, +`50 Coins`, `1 Hint`, `1 Double earnings`. For currency, use the amount the game already hands out +at that moment when the code shows one; otherwise propose a modest round figure and say it is a +default to correct. + +The reward the code grants is the game's own method (the existing revive, the existing add-coins +call), passed as the reward callback. Never invent game logic to match the reward, because the +user owns their economy. + +## Banner: usually off, and how to say so + +For a gameplay-heavy game a banner takes permanent screen space. Default it to off and give the +reason in one clause ("a portrait runner has no screen area to spare") rather than silently omitting +it. Mention an off placement once, in the proposal, then stop: it gets no code and no checklist row +unless the user turns it on. + +Turn it on when the game has a static screen where the player lingers (an idle game's main screen, +a shop, a lobby), and name that screen. + +## Shifting the balance with the user's goal + +Map the Step 2 goal onto the proposal by changing numbers and adding or dropping placements, never +by removing a guard: + +- **Balanced** (and "Not sure yet"): the templates as written. Interstitial gap 5 to 7 minutes, + 2 to 3 rewarded placements, banner only on a static screen. +- **Revenue-focused**: start interstitials at run 2, gap 3 to 5 minutes, add a second or third + rewarded placement at a different moment, and propose a banner at the bottom of the gameplay + screen, as `best-practices.md` does for this goal; when it would cover controls or the play area, + propose it on the menus instead and say why. Say plainly that players will + see more ads, which can cost retention, and that it can be tuned back once dashboard data exists. + Never say it will earn more. +- **UX-focused**: rewarded only, 1 to 2 placements, every one opt-in. Interstitials at session + boundaries only, or none; banner off or menu only. Say that players will see fewer ads. + +## Bid floors stay optional + +Do not put bid floors in the proposal. Say once that they are skipped by default and that Step 9 +offers them as an optional setting, because a floor set before the app has dashboard data mostly +lowers fill. + +## The proposal table + +Open with one sentence summarising the proposal, then one table, one row per enabled placement. +The Moment column names the action that fires the ad (a button pressed, a screen closing, a scene +loading): "Player leaves the victory screen", "Restart pressed", never "on the victory screen", +because an ad "on" a screen fires while the player is still reading it: + +| Placement | Format | Moment (on screen) | Rule | Where in code | +|---|---|---|---|---| +| Revive after death | Rewarded | Player dies; Revive button on the death screen | One per run; reward 1 Revive | `DeathScreen.OnReviveClicked()` at `Assets/Scripts/UI/DeathScreen.cs:27` | +| Between runs | Interstitial | Run ends, back to the menu | From run 4; at most one every 6 min; never after a rewarded | `RunManager.ReturnToMenu()` at `Assets/Scripts/RunManager.cs:88` | + +After the table, add at most four short lines: placements that need UI the user adds, any game-code +change a reward needs (for example "Double coins needs a small `Economy.DoubleLastReward()` added +to `Assets/Scripts/Economy.cs`, because nothing in the game doubles a payout today"), any placement +proposed as off with its reason, and that bid floors are skipped. The user approves the game-code +change together with the placement, so Step 9 never springs it on them. Then ask the approval +question in workflow Step 8. + +When the user edits the proposal, apply the edit, show only the changed rows, and ask again. Nothing +is implemented before the user approves the current version, because an edit can change which +files Step 9 touches. + +## Wiring an approved placement in Step 9 + +The ad code (built from `rewarded-api.md`, `interstitial-api.md` and `banner-api.md`, in the code +organization the user picks) owns everything about the ad: loading, showing, the cap and every guard. +The user's own method gains **exactly one call into it**, and nothing else changes — with one +exception: when the game has no method that grants the reward a placement promises (nothing doubles +the payout, nothing adds a hint), the ad code's reward callback needs a **minimal reward hook** in the +economy code — one small method or flag, nothing more — and only one that the Step 8 proposal listed +and the user approved. Disclose it in the Step 9 file list with its `file:line`, because it is a +change to the game's rules, not to the ad code. This procedure +applies only when the user chose an organization option that puts you in their files (options 1, 2 +and 4 in Step 9); under option 3, "Just show me the code snippets", produce a call-site snippet per +approved location, labelled with its `file:line`, and do not edit any gameplay script: + +1. Before editing a game script, list the files you will change, because they are the user's code, + and make a rollback point: under version control, ask the user to commit (or confirm the files are + committed) before you edit; without version control, copy each file you will change to a folder + outside `Assets/`, for example `/LevelPlayBackups/`, because Unity imports anything under + `Assets/` and a copy there would get its own `.meta` file. Tell the user the copy's path and that + restoring is replacing the edited file with it. +2. Read the method at the cited `file:line` again, because the file may have changed since Step 2. +3. Insert one call. For an interstitial, at the moment itself. When that moment goes on to load a + scene (`ReturnToMenu()` ending in `SceneManager.LoadScene`), the load must wait for the ad: give + the ad code a show call that takes a continuation and invokes it exactly once on every path: + from `OnAdClosed` or `OnAdDisplayFailed` once a show has started, and at once on every path that + skips the ad — not ready, placement or dashboard cap active, the rule's own cap, the manager + missing — because a skipped ad fires no callback and the player would stay on the results + screen. Then pass the scene load as that continuation, because `ShowAd()` returns before the ad + closes and a load that runs immediately tears the ad down with the scene. Keep the manager alive across scenes (the startup-scene object + with `DontDestroyOnLoad`, as the reference places it), because a scene-scoped manager's + `OnDestroy()` destroys the ad mid-display. For a rewarded placement, inside the button's press + handler, binding the reward to this placement at show time. With the reference's multi-placement + manager, first add a public show method for the approved placement (for example + `ShowAdForRevive()` calling its private `ShowAdWithPlacement("revive_after_death")`) and a + matching case in its `OnAdRewarded` dispatch that calls the game's reward method, because the + reference's `hints` / `extra_lives` / `bonus_coins` cases are examples, not placements a script + can call; then wire the button handler to that public method. With the single-placement manager, + pass the reward callback into the show call. Either way each reward event resolves against the + placement that produced it. Never overwrite a pending reward callback from another button, and ignore a press while a + show is pending, because `OnAdRewarded` can arrive after `OnAdClosed` and a shared, replaced + callback would hand the first ad's reward to the second button. First read what the handler + does today: if it already grants the reward directly (a `RevivePlayer()` call, a hint added), move + that grant into the reward callback so it runs only after the ad rewards, because leaving it in + place beside the ad call grants the reward twice, or for free when the ad fails. Move with it every + statement that assumes the reward happened — closing the death screen, resuming the game, hiding + the button — because a `Hide()` left in the handler closes the screen while the player is still + dead when no ad is ready. Keep any path that does not depend on the ad (a paid revive, a free hint + the game already gives) as its own branch. When no ad is available, leave the player where they + were with a visible result (the button disabled or a short "No ad available" state), never a + closed screen and no reward, and fall through to the ad-free path if the game has one. +4. Guard the call against a missing reference to the ad manager, so the game still runs before the + user wires the manager in a scene; when the guard trips, run the continuation (the scene load, + the game's own path) directly, so a missing manager skips the ad rather than the transition. +5. Keep the method's name, signature and callers, and change nothing in the file outside it; the + only edits inside it are the single ad call and the statements step 3 moves into the callback. + +Before a rewarded edit, check the hook is a press handler (an `onClick` listener, a `...Clicked()` +or `...Pressed()` method a button calls). If it is the moment itself, make no edit and tell the user +where the call belongs. + +## Adding a format later + +Do not repeat the profile. Re-read `Packages/packages-lock.json` to confirm the SDK is still +resolved, re-read the method you would hook, derive the new placement from this reference, show it +as a one-row proposal for approval, then follow "Adding More Ad Formats Later" in the workflow. + +## Worked examples + +**Endless runner, about 30-second runs, coin economy, Revive button found.** Summary: a rewarded +revive on death plus a capped interstitial between runs; Balanced goal. + +| Placement | Format | Moment (on screen) | Rule | Where in code | +|---|---|---|---|---| +| Revive after death | Rewarded | Player dies; Revive button on the death screen | One per run; reward 1 Revive | `DeathScreen.OnReviveClicked()` at `Assets/Scripts/UI/DeathScreen.cs:27` | +| Between runs | Interstitial | Results screen, back to the menu | From run 4; at most one every 6 min; never after a rewarded | `RunManager.ReturnToMenu()` at `Assets/Scripts/RunManager.cs:88` | + +Banner off: a portrait runner has no screen area to spare. Bid floors skipped. + +**Level-based puzzle, 2-minute levels, hint counter, no free-hint button, existing in-app +purchases.** Summary: a rewarded hint plus an interstitial on level complete; UX-focused goal. + +| Placement | Format | Moment (on screen) | Rule | Where in code | +|---|---|---|---|---| +| Free hint | Rewarded | Hint counter at zero; level screen, button to add | 3 per day; reward 1 Hint | None: needs a Free hint button on the level screen. You add it; Step 9 writes the call for its handler | +| Level complete | Interstitial | Level-complete screen, session end only | Once per session, never after a rewarded | `LevelManager.CompleteLevel()` at `Assets/Scripts/LevelManager.cs:142` | + +Note that the game sells hint packs: do not show the free-hint offer to a player who has hints +left, so the offer does not undercut the purchase. + +**Idle incremental, long sessions, deep currency economy, offline-earnings popup with a Claim 2x +button.** Summary: rewarded multipliers plus a banner on the main idle screen, no interstitials; +Balanced goal. + +| Placement | Format | Moment (on screen) | Rule | Where in code | +|---|---|---|---|---| +| Offline earnings boost | Rewarded | Player returns; Claim 2x on the offline-earnings popup | Once per session; reward 1 Double earnings | `OfflinePopup.OnClaimDoubleClicked()` at `Assets/Game/UI/OfflinePopup.cs:53` | +| Main screen banner | Banner | Main idle screen, bottom | Hidden while any popup is open | Show in `MainScreen.OnEnable()` at `Assets/Game/UI/MainScreen.cs:18`; hide in `MainScreen.OnDisable()` at `Assets/Game/UI/MainScreen.cs:24` | + +Interstitials off: an idle game has no run or level break to place one at, so any forced ad +would interrupt the player. diff --git a/skills/using-unity/references/levelplay-unity-integration/references/privacy-settings.md b/skills/using-unity/references/levelplay-unity-integration/references/privacy-settings.md index d0e3d13..4e77917 100644 --- a/skills/using-unity/references/levelplay-unity-integration/references/privacy-settings.md +++ b/skills/using-unity/references/levelplay-unity-integration/references/privacy-settings.md @@ -18,21 +18,23 @@ LevelPlay SDK provides APIs to help facilitate privacy regulation requirements including GDPR, CCPA, and COPPA. These settings must be configured before SDK initialization. +When talking to the user, name these settings only. Don't explain what a law is or who or where it applies to, and don't say which settings the user needs; point to [Regulation Advanced Settings for Unity](https://docs.unity.com/en-us/grow/levelplay/sdk/unity/regulation-advanced-settings) and the user's own legal counsel. + **SDK Version Requirement:** SDK 9.4.0+ for current APIs (older deprecated APIs available in SDK 9.3.0 and lower) ## Quick Reference -| Regulation | SDK 9.5.0+ API | SDK 9.4.x API | When to Use | -|------------|---------------|---------------|-------------| -| **GDPR** | `LevelPlayPrivacySettings.SetGDPRConsent(bool)` | `LevelPlayPrivacySettings.SetGDPRConsents(Dictionary)` | EU users, requires explicit consent | -| **CCPA** | `LevelPlayPrivacySettings.SetCCPA(true)` | `LevelPlayPrivacySettings.SetCCPA(true)` | California users opting out of data sale | -| **COPPA** | `LevelPlayPrivacySettings.SetCOPPA(true)` | `LevelPlayPrivacySettings.SetCOPPA(true)` | Apps directed at children under 13 | +| Setting | SDK 9.5.0+ API | SDK 9.4.x API | +|---------|---------------|---------------| +| **GDPR consent** | `LevelPlayPrivacySettings.SetGDPRConsent(bool)` | `LevelPlayPrivacySettings.SetGDPRConsents(Dictionary)` | +| **CCPA** | `LevelPlayPrivacySettings.SetCCPA(true)` | `LevelPlayPrivacySettings.SetCCPA(true)` | +| **COPPA** | `LevelPlayPrivacySettings.SetCOPPA(true)` | `LevelPlayPrivacySettings.SetCOPPA(true)` | -## GDPR Consent Management +For what each setting covers, see [Regulation Advanced Settings for Unity](https://docs.unity.com/en-us/grow/levelplay/sdk/unity/regulation-advanced-settings). -### What is GDPR? +## GDPR Consent Management -The General Data Protection Regulation (GDPR) is a European Union privacy law requiring explicit user consent for data collection and processing. Apps serving EU users must implement GDPR consent flows. +For what this setting covers, see [Regulation Advanced Settings for Unity](https://docs.unity.com/en-us/grow/levelplay/sdk/unity/regulation-advanced-settings). ### Set GDPR Consent @@ -115,23 +117,23 @@ public class GDPRConsentManager : MonoBehaviour void Start() { - // Check if user is in GDPR region (EU) - if (IsUserInGDPRRegion()) + // Your own logic decides whether to request GDPR consent + if (ShouldRequestGDPRConsent()) { // Show consent dialog and get user's answer ShowConsentDialog(); } else { - // Not in GDPR region, initialize normally + // GDPR consent not requested; initialize normally InitializeLevelPlay(); } } - private bool IsUserInGDPRRegion() + private bool ShouldRequestGDPRConsent() { - // Implement your region detection logic - // Options: IP geolocation, device locale, or third-party consent SDK + // Implement your own logic for when this setting applies + // For example, a consent management platform return false; // Placeholder } @@ -189,9 +191,7 @@ LevelPlayPrivacySettings.SetGDPRConsent(false); // User revoked consent ## CCPA Compliance -### What is CCPA? - -The California Consumer Privacy Act (CCPA) gives California residents the right to opt out of the "sale" of their personal information. Apps must provide a "Do Not Sell My Personal Information" option. +For what this setting covers, see [Regulation Advanced Settings for Unity](https://docs.unity.com/en-us/grow/levelplay/sdk/unity/regulation-advanced-settings). ### Set CCPA Opt-Out (SDK 9.4.0+) @@ -223,8 +223,8 @@ public class CCPAComplianceManager : MonoBehaviour void Start() { - // Check if user is in California - if (IsUserInCalifornia()) + // Your own logic decides whether the CCPA setting applies + if (ShouldApplyCCPA()) { // Load previously saved opt-out preference userOptedOut = PlayerPrefs.GetInt("CCPA_OptOut", 0) == 1; @@ -243,10 +243,9 @@ public class CCPAComplianceManager : MonoBehaviour InitializeLevelPlay(); } - private bool IsUserInCalifornia() + private bool ShouldApplyCCPA() { - // Implement your region detection logic - // Options: IP geolocation, device locale + // Implement your own logic for when this setting applies return false; // Placeholder } @@ -288,9 +287,7 @@ public class CCPAComplianceManager : MonoBehaviour ## COPPA Compliance -### What is COPPA? - -The Children's Online Privacy Protection Act (COPPA) is a US federal law protecting children under 13. Apps directed at children must not collect personal information without parental consent. +For what this setting covers, see [Regulation Advanced Settings for Unity](https://docs.unity.com/en-us/grow/levelplay/sdk/unity/regulation-advanced-settings). ### Set Child-Directed Treatment (SDK 9.4.0+) @@ -299,7 +296,7 @@ Indicate that your app is directed at children: ```csharp using Unity.Services.LevelPlay; -// App is directed at children under 13 (call BEFORE SDK initialization) +// App is directed at children (call BEFORE SDK initialization) LevelPlayPrivacySettings.SetCOPPA(true); ``` @@ -351,13 +348,12 @@ public class COPPACompliantInitializer : MonoBehaviour If your app is child-directed: -1. **Disable personalized ads**: COPPA requires non-personalized ads only -2. **Google Play Families Policy**: If targeting children on Google Play: +1. **Google Play Families Policy**: If targeting children on Google Play: - Set COPPA flag: `LevelPlayPrivacySettings.SetCOPPA(true)` - Review Google Play Families requirements for child-directed apps - Test thoroughly before submission -3. **App Store age ratings**: Set appropriate age ratings in both app stores -4. **Privacy policy**: Clearly state data collection practices for children +2. **App Store age ratings**: Set appropriate age ratings in both app stores +3. **Privacy policy**: Clearly state data collection practices for children --- @@ -385,8 +381,8 @@ public class PrivacyComplianceManager : MonoBehaviour LevelPlayPrivacySettings.SetCOPPA(true); } - // 2. GDPR (if user in EU) - if (IsUserInGDPRRegion()) + // 2. GDPR consent (if your logic requests it) + if (ShouldRequestGDPRConsent()) { if (HasStoredGDPRConsent()) { @@ -400,8 +396,8 @@ public class PrivacyComplianceManager : MonoBehaviour } } - // 3. CCPA (if user in California) - if (IsUserInCalifornia()) + // 3. CCPA (if your logic applies it) + if (ShouldApplyCCPA()) { bool ccpaOptOut = LoadCCPAOptOut(); if (ccpaOptOut) @@ -429,15 +425,15 @@ public class PrivacyComplianceManager : MonoBehaviour return PlayerPrefs.GetInt("CCPA_OptOut", 0) == 1; } - private bool IsUserInGDPRRegion() + private bool ShouldRequestGDPRConsent() { - // Implement region detection + // Implement your own logic for when this setting applies return false; } - private bool IsUserInCalifornia() + private bool ShouldApplyCCPA() { - // Implement region detection + // Implement your own logic for when this setting applies return false; } @@ -519,14 +515,13 @@ LevelPlay.SetMetaData("is_child_directed", "false"); 1. **Call before initialization**: All privacy settings must be applied before `LevelPlay.Init()` 2. **Persist user choices**: Store consent preferences and reapply on each app launch -3. **Detect user region**: Use geolocation or device locale to determine applicable regulations -4. **Provide UI controls**: Give users easy access to privacy settings -5. **Respect user choices**: Honor opt-outs and consent denials -6. **Update promptly**: When user changes preferences, apply immediately via privacy APIs -7. **Test thoroughly**: Test your privacy settings in all supported regions -8. **Document clearly**: Include privacy policy links in your app -9. **Use consent management platforms**: Consider third-party CMPs for complex consent requirements -10. **Stay updated**: Privacy regulations evolve, monitor SDK updates for compliance changes +3. **Provide UI controls**: Give users easy access to privacy settings +4. **Respect user choices**: Honor opt-outs and consent denials +5. **Update promptly**: When user changes preferences, apply immediately via privacy APIs +6. **Test thoroughly**: Test every combination of privacy settings your app uses +7. **Document clearly**: Include privacy policy links in your app +8. **Use consent management platforms**: Consider third-party CMPs for complex consent requirements +9. **Stay updated**: Privacy regulations evolve, monitor SDK updates for compliance changes --- @@ -586,8 +581,5 @@ private void OnInitSuccess(LevelPlayConfiguration config) ## Additional Resources -- [LevelPlay Privacy Documentation](https://docs.unity.com/en-us/grow/levelplay) -- [GDPR Overview](https://gdpr.eu/) -- [CCPA Information](https://oag.ca.gov/privacy/ccpa) -- [COPPA Requirements](https://www.ftc.gov/legal-library/browse/rules/childrens-online-privacy-protection-rule-coppa) +- [Regulation Advanced Settings for Unity](https://docs.unity.com/en-us/grow/levelplay/sdk/unity/regulation-advanced-settings) - [Google Play Families Policy](https://support.google.com/googleplay/android-developer/answer/9893335) diff --git a/skills/using-unity/references/levelplay-unity-integration/references/project-inference.md b/skills/using-unity/references/levelplay-unity-integration/references/project-inference.md new file mode 100644 index 0000000..2c35237 --- /dev/null +++ b/skills/using-unity/references/levelplay-unity-integration/references/project-inference.md @@ -0,0 +1,314 @@ +# Profiling a Unity Project Before Proposing Ads + +What to read, what to search for, and what each signal means, so Step 2 builds a short project +profile from a handful of targeted reads instead of a crawl through the project. Step 8 builds its +placement proposal from this profile, so every finding here should name the file and line it came +from. + +This step only reads files. Do not edit anything while profiling, because the user has not approved +any change yet. + +## Contents + +- [Budget and order](#budget-and-order) +- [Game type](#game-type) +- [Session length](#session-length) +- [Key moments](#key-moments) +- [UI a placement needs](#ui-a-placement-needs) +- [Economy](#economy) +- [Existing monetization](#existing-monetization) +- [Target platforms](#target-platforms) +- [Audience](#audience) +- [The readout](#the-readout) +- [Confidence and how to phrase it](#confidence-and-how-to-phrase-it) +- [When the project tells you nothing](#when-the-project-tells-you-nothing) + +## Budget and order + +Aim for roughly ten reads, not a hundred. Work in this order, and stop on a row as soon as it is +settled: + +1. **Scene names.** Read `ProjectSettings/EditorBuildSettings.asset` for the scenes in the build; + if it lists none, list the `.unity` files under `Assets/`. Names alone establish structure. +2. **`ProjectSettings/ProjectSettings.asset`** for the product name and the per-platform + application identifiers. +3. **`Packages/manifest.json` and `Packages/packages-lock.json`** for the packages the project uses. +4. **One search pass over the game's own scripts** (`Assets/**/*.cs`) with the patterns below. + Leave out `Library/`, `Packages/` and third-party folders under `Assets/` (for example + `Assets/Plugins/` or an imported asset's own folder), because a hit there is not the game's code. +5. **Two or three whole-file reads** of the scripts the search ranked highest: usually the player + controller, a game manager, and whatever owns the score or currency. These reads also confirm + each key moment before you cite it. + +Never read every script. The profile has seven rows, and a wrong guess costs the user one correction, +which is cheaper than a long silent crawl. + +The patterns below are extended regular expressions. With `grep`, for example: +`grep -rnE --include='*.cs' '\b(Die|OnDeath|GameOver)\b' Assets`. Use `|` for alternation, not +`\|`, because the escaped form matches a literal bar under extended syntax and finds nothing. When +you need to know which of two literals is present, search for each separately, so each result is +quotable on its own. + +## Game type + +**Scene names** are the strongest single signal and cost nothing: + +| Scene names like | Suggests | +|---|---| +| `Main`, `Game`, `GameOver` only | A single-loop arcade game or runner | +| `Level_01`, `Level_02`, `LevelSelect` | Level-based progression | +| `Menu`, `Shop`, `Inventory`, `Base` | An economy-driven sim or builder | +| `Lobby`, `Match`, `Results` | Match-based, possibly multiplayer | +| `Intro`, `Chapter_*`, `Dialogue` | Narrative | + +**Class names** that discriminate genre: + +``` +class\s+\w*(Spawner|Runner|Obstacle|Endless|Generator) -> runner, endless +class\s+\w*(Level|Puzzle|Grid|Board|Tile)Manager -> puzzle, board +class\s+\w*(Idle|Production|Tick|Offline) -> idle, incremental +class\s+\w*(Weapon|Enemy|Health|Damage) -> action, shooter +class\s+\w*(Dialogue|Story|Chapter|Quest) -> narrative +``` + +**Packages** are a cross-check: `com.unity.netcode.gameobjects`, `com.unity.services.lobby` or +`com.unity.services.multiplayer` in `Packages/manifest.json` points at match-based multiplayer. + +## Session length + +Derive it, and say what it was derived from. In order of reliability: + +1. **An explicit timer or run length** in code: a countdown, a `roundDuration`, a `timeLimit` + serialized field. Read the value. +2. **Level count and pacing**: a level-based game with 60 short levels has minute-scale sessions. +3. **Loop shape**: an endless runner with a death-and-restart cycle and no timer has runs of tens of + seconds; an idle game with offline-earnings logic has sessions of minutes with long gaps. + +``` +(timeLimit|roundDuration|sessionLength|matchDuration|countdown) +(offlineEarnings|lastPlayedTime|TimeSpan|DateTime\.(Now|UtcNow)) +``` + +The second pattern also tells you whether the game models time away, which is the idle-game tell. + +## Key moments + +These are where ads go: Step 8 anchors each placement to one, and Step 9 puts the ad call there (or, +for a rewarded ad, in the button handler that accepts it). This row deserves the most care. Find the +method, and name it: "death at `PlayerHealth.Die()`" is worth far more than "death". + +``` +(void|public|private|protected).*\b(Die|OnDeath|GameOver|PlayerDied|HandleDeath)\b +\b(LevelComplete|OnLevelFinished|WinLevel|StageClear|OnVictory)\b +\b(Restart|Retry|PlayAgain|ReturnToMenu|BackToMenu)\b +\bSceneManager\.LoadScene\b +\b(OnPause|Pause|Resume|OnApplicationPause)\b +\b(LevelUp|OnLevelUp|Unlock|OpenShop|ShowShop)\b +``` + +Map what you find: + +- A death or fail method is where a rewarded revive or continue is **offered**. The placement's + call goes in the Revive button's handler, found per [UI a placement needs](#ui-a-placement-needs), + never in the death method itself. +- A level-complete or victory method is an interstitial moment. +- A restart or return-to-menu path is the between-runs interstitial moment. +- A level-up, unlock or shop method is a rewarded moment (bonus currency, a speed-up), again + through a button. +- A pause handler matters because no forced ad may fire while the player has paused the game. + +**Record each moment as `Class.Method` at `file:line`**, straight from the search hit: the path is +project-relative under `Assets/`, the line is the method's declaration. Hold every entry to these +rules: + +- **Confirm before you cite.** Read the method and enough around it to see the enclosing class and + what it does, because a match on `Die` in a comment, a string or `EnemyHealth.Die` is not the + player's death. Only a method you have read goes in the profile. +- **Never invent a symbol.** No guessed class, no method you expect to exist, no path you did not + see in a result, because Step 9 edits exactly the location you cite. A moment with no confirmed + method is named in plain words ("return to menu") with no location, and Step 8 says so. +- **Prefer the most specific method**: the one where the moment happens (`PlayerHealth.Die`), not a + dispatcher that eventually reaches it (`GameManager.Update`), and not a Unity callback shared by + many moments (`OnTriggerEnter2D`) when a named handler exists. +- **Keep the alternates.** When two methods fit one moment, name the chosen one first and the others + after it ("death at `PlayerHealth.Die()`, also `GameManager.OnGameOver()`"), so a wrong pick is one + correction away. + +## UI a placement needs + +A rewarded ad is a button the player presses, so a moment is only half a placement: a results screen +is where a **Double coins** offer would go, not proof that a Double coins button exists. Before +Step 8 names a button, check that it exists: + +1. **All of the game's own scripts**, not only the folder of the class that shows the moment, + because a view class often lives apart from the manager that owns the moment (`UI/RewardScreen/` + next to `Managers/`). Search `Assets/**/*.cs` (minus third-party folders) for buttons and + handlers: + ``` + (Button|onClick|OnClick|AddListener|clicked) + (Double|Multiply|2x|x2|Bonus|Watch|Revive|Continue|Hint|Free|Restart|Retry|Return|Home|Again|Replay|Next)\w* + ``` + The second pattern names the screen's own buttons (Restart, Retry, Return, Next) as well as + reward words, because a lose or results screen that no script shows by name is found through the + buttons on it, and that screen is where the rewarded offer goes. +2. **Its prefab, scene or UXML**, because the UI itself lives there. For uGUI, search `.prefab` and + `.unity` files for + `m_Name: .*(Double|2x|x2|Bonus|Watch|Revive|Continue|Hint|Restart|Retry|Return|Home|Again|Replay|Next)`. + A button wired in the Inspector has no `AddListener` in code: search the same files for + `m_MethodName:` followed by the handler's name. For UI Toolkit, search `.uxml` files for a + `Button` element with a matching `name`. +3. **Record the finding with the moment**: "results screen `ResultsPanel.Show()` has a Double coins + button, handled by `ResultsPanel.OnDoubleClicked()` at `Assets/UI/ResultsPanel.cs:41`", or "I + couldn't find a Double coins button (searched all scripts and `Results.prefab`)". + +**A miss is "I couldn't find one", never "there is none."** A search can miss a button whose label +or folder you did not guess, so phrase the miss as what you searched, and let the readout invite the +correction ("if the game has one, tell me its script"). Still never write a profile row or a +proposal line that implies the button exists when these reads did not find it, because Step 9 would +then wire an ad to UI that is not there. Step 8 proposes such a placement as needing UI the user +adds, or hooks it to the button the user names. + +## Economy + +``` +\b(coins?|gems?|currency|gold|credits?|lives|energy|stars|hints?)\b +\bPlayerPrefs\.(Get|Set)(Int|Float|String)\b +class\s+\w*(Shop|Store|Upgrade|Inventory|Wallet|SaveData) +\b(Continue|Revive|ExtraLife|AddLife)\b +``` + +What to conclude: + +- A named currency plus a shop or upgrade class means a real economy: rewarded currency and + multipliers have something to attach to. +- Saved score or currency (`PlayerPrefs` writes, a save class) means progression persists, which + gives a rewarded reward something to keep. +- Lives, energy or an existing continue path give a rewarded continue a reward the game already + knows how to grant. +- A score with no currency and no shop means the only durable reward is a revive or a continue. Say + "score only, no currency" rather than "none", because it leads to a different proposal. + +## Existing monetization + +Read `Packages/packages-lock.json` first, because it records what is actually installed; then search +the code, because a package can be installed and unused: + +``` +(LevelPlay|IronSource|LevelPlayRewardedAd|LevelPlayInterstitialAd|LevelPlayBannerAd) +\bIronSource\.Agent\b +(UnityEngine\.Advertisements|Advertisement\.Show) +(UnityEngine\.Purchasing|IStoreListener|IAPButton|CodelessIAPButton) +``` + +Report what exists by name, and route on what you find: + +- **Package installed, no LevelPlay code** (`com.unity.services.levelplay` in the lock file and no + hit in the code): this is still a fresh integration, because the lock entry only records that the + package resolved. Report it as installed; Step 3 confirms the install and continues. +- **LevelPlay code present**: not a fresh integration. `IronSource.Agent` calls mean a migration: + say so and offer the migration path from Step 0. Current Ad Unit API code means the user is adding + to an existing setup: Step 9 then starts from their code. +- **Unity Ads** (`com.unity.ads`, `UnityEngine.Advertisements`): offer the Unity Ads migration from + Step 0. +- **Existing placements are audited, not inherited.** For each ad call the search finds, whatever + the SDK, read the method around it and record its format, what triggers it, and what the game + grants when it closes. Check each against the placement guards Step 8 applies (a rewarded ad + only from a press the player chose; a forced ad only at a transition, never mid-action; never + one directly after the other). + One that breaks a guard (an interstitial that fires when the player walks up to an object or on a + timer and then pays out a reward; a rewarded ad shown from a death method rather than a button; a + banner over controls) goes in the readout as found **and** as needing a change, and Step 8 + proposes the conversion at the same moment (a forced ad that pays a reward becomes a rewarded + offer behind a press there) rather than a second placement beside it. Keeping it as it is stays + the user's call, made on the proposal, never the default. +- **In-app purchases** (`com.unity.purchasing`, `UnityEngine.Purchasing`): note it, because a + rewarded offer must not undercut a product the game sells (a hint pack, extra lives). +- **Another ad SDK**: report that it is present and move on. Do not describe or compare it, for the + same reason the skill never characterizes other mediation products. + +## Target platforms + +LevelPlay runs on Android and iOS only, so these are the only platforms the profile reports. Read +the `applicationIdentifier` entries in `ProjectSettings/ProjectSettings.asset` (iOS appears there as +`iPhone`): an entry that is not the default `com.DefaultCompany.*` identifier suggests the platform +was prepared. An `Assets/Plugins/Android/` or `Assets/Plugins/iOS/` folder corroborates. Any other +target (Standalone, WebGL) is named as not covered by LevelPlay. + +Treat this row as inferred. Step 4 still asks the platform question, because the active build +target is not recorded in a readable project file. + +## Audience + +Whether the game is directed at children changes the proposal more than any other row: it rules +formats out before the goal sets any number (Step 8 has rules for child-directed games), it +makes the `SetCOPPA(true)` call in Step 6.5 required, and on the API +path it sets the app's `coppa` flag in Step 5. The project files rarely state it, so this row is +**asked, not inferred**, in the same message as the goal question: + +**"Who is the game for: a general audience, children, or both (mixed)?"** + +The user's answer is the only source. Whether a game is child-directed is a determination the +developer makes, with `references/privacy-settings.md` (COPPA Compliance) and their own counsel; +the agent never makes it for them and never states what a law permits or requires. Signals in the +project (a toddler-style soundboard or free-play toy with no fail state, nursery art, `Kids`, +`Toddler`, `ChildSafe` or `Parental` in scene, class or product names) mean the question is asked +with the signal named, so the user can confirm it in a word ("the product name is Turtle Fishing +and there is no fail state, which reads like a game for young children: is it directed at +children?"), never that the row is filled in without asking. + +Record the answer as `General`, `Child-directed` or `Mixed`, marked as from the user. If the user +does not know, record `Unanswered`, propose for a general audience in Step 8 and say so, and say +that the answer is needed before Step 6.5 and before any app is created in Step 5. + +## The readout + +Open with one line saying the profile was built from the project's files without changing +anything. Right after that line, and before the table, show this notice exactly as written. Do not +reword, shorten, summarize, or translate it. Show it the first time the profile appears in a +conversation. + +Please read everything carefully. You are solely responsible for reviewing, validating, and accepting any actions taken or content produced as a result of these interactions. You are responsible for the results of any automated action initiated through this skill, including changes to campaigns, budgets, bids, or spend, and any associated financial impact. + +Show the profile as one short table before you ask anything, so the user can correct it in one +reply. Seven rows, in this order, each with its evidence: + +| Row | What it holds | +|---|---| +| Game type | The closest genre, and the scenes or classes it came from | +| Session length | The estimate, and what it was derived from | +| Key moments | Each moment as `Class.Method()` at `file:line`, alternates after; the button found or missing for each rewarded moment | +| Economy | Currency, lives, continue, shop, or "score only, no currency" | +| Existing monetization | Each package or SDK found, by name, or "none found"; each ad call found, with its trigger, and whether it breaks a guard | +| Target platforms | Android, iOS, or both, with the evidence; other targets named as not covered | +| Audience | "Asked below", with any signal the files show; the user's answer replaces it | + +Keep it to the table and one line after it. A correction from the user replaces the row; restate +only the corrected rows. + +## Confidence and how to phrase it + +Name the evidence instead of hedging: "about 30-second runs, from `ObstacleSpawner` and the restart +loop". That invites a correction rather than making the user feel they are contradicting you, and a +wrong inference is then obviously wrong rather than mysteriously wrong. + +Do not hedge every row. A row read straight out of `ProjectSettings.asset` or the lock file is a +fact and reads like one. + +## When the project tells you nothing + +A very early prototype may have one scene, one script and no loop. Say that directly in the readout, +then ask at most these three questions in one message, before the goal question, because they are +the only facts the proposal cannot do without: + +1. "What does one play session look like: runs, levels, matches, or something else, and roughly how + long?" +2. "Where does a run or level end, and where can the player fail?" +3. "Does the game have a currency, lives, or hints a reward could give?" + +Use the answers in place of the missing rows, marked as from the user. Do not invent scripts, +methods or UI to fill the gaps, because Step 9 would wire ads to code that does not exist. If the +user cannot answer either, Step 8 names a single opt-in rewarded placement as **deferred**: no code +location, no reward, and not part of what the user approves for implementation, because Step 9 needs +a press handler and the game's reward method and neither exists yet. Say that the proposal resumes +once the game has a run or level end and a button a player can press, and stop there; do not ask +for implementation approval of a deferred placement. diff --git a/skills/using-unity/references/levelplay-unity-integration/references/testing-and-validation.md b/skills/using-unity/references/levelplay-unity-integration/references/testing-and-validation.md index b39be20..2c858b4 100644 --- a/skills/using-unity/references/levelplay-unity-integration/references/testing-and-validation.md +++ b/skills/using-unity/references/levelplay-unity-integration/references/testing-and-validation.md @@ -1,6 +1,8 @@ # LevelPlay Testing and Validation -Detailed guidance for the two validation approaches referenced from Step 10 of SKILL.md: mock ads in +> Relative file paths in this reference (for example `ios-setup.md`) resolve to the skill directory's `references/` folder. + +Detailed guidance for the two validation approaches referenced from Step 10 of the workflow: mock ads in the Unity Editor (early development) and the LevelPlay Test Suite (integration validation on device). Read this when the user is testing their integration, asks how mock ads work, or is setting up the Test Suite. @@ -151,6 +153,18 @@ Suite will silently never launch. **Important**: Remove both lines before your production release. Test Suite should only be used during development and testing. +**Optional safety net:** wrap each of the two lines in a compile guard, so a forgotten removal cannot +reach players, because release builds without **Development Build** compile them out: + +```csharp +#if UNITY_EDITOR || DEVELOPMENT_BUILD +LevelPlay.SetMetaData("is_test_suite", "enable"); +#endif +``` + +Wrap `LevelPlay.LaunchTestSuite();` the same way. The guard is a backstop, not a replacement: still +remove both lines before release. + ## Test Suite Initializer Template **Don't have a `LevelPlayInitializer.cs` yet?** Use this complete template: diff --git a/skills/using-unity/references/levelplay-unity-integration/references/troubleshooting.md b/skills/using-unity/references/levelplay-unity-integration/references/troubleshooting.md index 7bfacff..a68bcb9 100644 --- a/skills/using-unity/references/levelplay-unity-integration/references/troubleshooting.md +++ b/skills/using-unity/references/levelplay-unity-integration/references/troubleshooting.md @@ -1,7 +1,7 @@ # LevelPlay Common Issues and Solutions Detailed troubleshooting for issues that can occur during integration, referenced from the Common Issues -table in SKILL.md. Read this when the user reports a compile error, a build failure, ads not loading, +table in the workflow. Read this when the user reports a compile error, a build failure, ads not loading, callbacks not firing, or a platform-specific build error. **Note**: This section addresses issues that can occur during integration. If you haven't started the