下列程式碼範例包含廣告單元 ID,可用於要求測試廣告。這類 ID 經過特別設定,可針對每項要求傳回測試廣告,而非實際廣告,因此可安心使用。
不過,在 Ad Manager 網頁介面註冊應用程式,並建立要在應用程式中使用的廣告單元 ID 後,請在開發期間明確將裝置設為測試裝置。
/21775744923/example/rewarded
初始化 Mobile Ads SDK
應用程式必須先呼叫 MobileAds.Initialize(),初始化 Mobile Ads SDK 之後,才能載入廣告。這項操作只需執行一次,且最好在應用程式啟動時執行。
usingGoogleMobileAds;usingGoogleMobileAds.Api;publicclassGoogleMobileAdsDemoScript:MonoBehaviour{publicvoidStart(){// Initialize the Google Mobile Ads SDK.MobileAds.Initialize((InitializationStatusinitStatus)=>
{// This callback is called once the MobileAds SDK is initialized.});}}
// Create our request used to load the ad.varadRequest=newAdRequest();// Send the request to load the ad.RewardedAd.Load("AD_UNIT_ID",adRequest,(RewardedAdad,LoadAdErrorerror)=>
{if(error!=null){// The ad failed to load.return;}// The ad loaded successfully.});
// Create and pass the SSV options to the rewarded ad.varoptions=newServerSideVerificationOptions{CustomData=""SAMPLE_CUSTOM_DATA_STRING""};rewardedAd.SetServerSideVerificationOptions(options);
rewardedAd.OnAdPaid += (AdValue adValue) =>
{
// Raised when the ad is estimated to have earned money.
};
rewardedAd.OnAdImpressionRecorded += () =>
{
// Raised when an impression is recorded for an ad.
};
rewardedAd.OnAdClicked += () =>
{
// Raised when a click is recorded for an ad.
};
rewardedAd.OnAdFullScreenContentOpened += () =>
{
// Raised when the ad opened full screen content.
};
rewardedAd.OnAdFullScreenContentClosed += () =>
{
// Raised when the ad closed full screen content.
};
rewardedAd.OnAdFullScreenContentFailed += (AdError error) =>
{
// Raised when the ad failed to open full screen content.
};
rewardedAd.OnAdFullScreenContentClosed+=()=>
{// Reload the ad so that we can show another as soon as possible.varadRequest=newAdRequest();RewardedAd.Load("AD_UNIT_ID",adRequest,(RewardedAdad,LoadAdErrorerror)=>
{// Handle ad loading here.});};
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-08-28 (世界標準時間)。"],[[["\u003cp\u003eThis guide provides step-by-step instructions for integrating rewarded ads from AdMob into a Unity app, enabling users to earn in-app rewards by interacting with ads.\u003c/p\u003e\n"],["\u003cp\u003eBefore implementation, ensure completion of the 'Get started' guide and initialize the Mobile Ads SDK at app launch using \u003ccode\u003eMobileAds.Initialize()\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThe key steps involve loading the rewarded ad, optionally validating server-side verification (SSV) callbacks, displaying the ad with a reward callback, listening to ad events, cleaning up the ad object, and preloading the next ad for a seamless user experience.\u003c/p\u003e\n"],["\u003cp\u003eRewarded ads are single-use objects, requiring a new \u003ccode\u003eRewardedAd\u003c/code\u003e object to be created for each ad request after displaying it.\u003c/p\u003e\n"],["\u003cp\u003eDevelopers are encouraged to always test with test ads during development and to preload ads in advance to ensure they are readily available when needed, optimizing user experience and reward delivery.\u003c/p\u003e\n"]]],[],null,["Select platform: [Android](/ad-manager/mobile-ads-sdk/android/rewarded \"View this page for the Android platform docs.\") [iOS](/ad-manager/mobile-ads-sdk/ios/rewarded \"View this page for the iOS platform docs.\") [Unity](/ad-manager/mobile-ads-sdk/unity/rewarded \"View this page for the Unity platform docs.\") [Flutter](/ad-manager/mobile-ads-sdk/flutter/rewarded \"View this page for the Flutter platform docs.\")\n\n\u003cbr /\u003e\n\nRewarded ads are ads that users have the option of interacting with in exchange\nfor in-app rewards. This guide shows you how to integrate rewarded ads from\nAdMob into a Unity app.\n\nThis guide explains how to integrate rewarded ads into a Unity app.\n\nPrerequisites\n\n- Complete the [Get started guide](/ad-manager/mobile-ads-sdk/unity/quick-start).\n\nAlways test with test ads\n\nThe following sample code contains an ad unit ID which you can use to request\ntest ads. It's been specially configured to return test ads rather than\nproduction ads for every request, making it safe to use.\n\nHowever, after you've registered an app in the\nAd Manager web interface and created your own ad unit\nIDs for use in your app, explicitly [configure your device as a test\ndevice](/ad-manager/mobile-ads-sdk/unity/test-ads#enable_test_devices) during\ndevelopment.\n\n`/21775744923/example/rewarded`\n\nInitialize the Mobile Ads SDK\n\nBefore loading ads, have your app initialize Google Mobile Ads SDK by calling\n`MobileAds.Initialize()`. This needs to be done only once, ideally at app launch. \n\n using GoogleMobileAds;\n using GoogleMobileAds.Api;\n\n public class GoogleMobileAdsDemoScript : MonoBehaviour\n {\n public void Start()\n {\n // Initialize Google Mobile Ads SDK.\n MobileAds.Initialize((InitializationStatus initStatus) =\u003e\n {\n // This callback is called once the MobileAds SDK is initialized.\n });\n }\n }\n\nIf you're using mediation, wait until the callback occurs before loading ads as\nthis will ensure that all mediation adapters are initialized.\n\nLoad the rewarded ad\n\nLoading a rewarded ad is accomplished using the static `Load()` method on the\n`RewardedAd` class. The loaded `RewardedAd` object is provided as a\nparameter in the completion handler. The following example loads a rewarded ad: \n\n // Create our request used to load the ad.\n var adRequest = new AdRequest();\n\n // Send the request to load the ad.\n RewardedAd.Load(\"\u003cvar translate=\"no\"\u003eAD_UNIT_ID\u003c/var\u003e\", adRequest, (RewardedAd ad, LoadAdError error) =\u003e\n {\n if (error != null)\n {\n // The ad failed to load.\n return;\n }\n // The ad loaded successfully.\n }); \n https://github.com/googleads/googleads-mobile-unity/blob/be5850e271b73dd450a89f44df67dac6b1f1712a/samples/HelloWorld/Assets/Snippets/RewardedAdSnippets.cs#L21-L33\n\nReplace \u003cvar class=\"readonly\" translate=\"no\"\u003eAD_UNIT_ID\u003c/var\u003e with your ad unit ID.\n| **Warning:** Attempting to load a new ad from the ad request completion block when an ad failed to load is strongly discouraged. If you must load an ad from the ad request completion block, limit ad load retries to avoid continuous failed ad requests in situations such as limited network connectivity.\n\n\n| **Tip:** You can use ad load calls to build up a cache of preloaded ads before you intend to show them, so that ads can be shown with zero latency when needed. Since ads expire after an hour, you should clear this cache and reload with new ads every hour.\n\n\u003cbr /\u003e\n\n\\[Optional\\] Validate server-side verification (SSV) callbacks\n\nApps that require extra data in [server-side verification](/admob/unity/ssv)\ncallbacks should use the custom data feature of rewarded ads.\nAny string value set on a rewarded ad object is passed to the `custom_data`\nquery parameter of the SSV callback. If no custom data value is set, the\n`custom_data` query parameter value won't be present in the SSV callback.\n\nThe following code sample demonstrates how to set the SSV options after the\nrewarded ad is loaded. \n\n // Create and pass the SSV options to the rewarded ad.\n var options = new ServerSideVerificationOptions\n {\n CustomData = \"\"\u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-n\"\u003eSAMPLE_CUSTOM_DATA_STRING\u003c/span\u003e\u003c/var\u003e\"\"\n };\n\n rewardedAd.SetServerSideVerificationOptions(options); \n https://github.com/googleads/googleads-mobile-unity/blob/be5850e271b73dd450a89f44df67dac6b1f1712a/samples/HelloWorld/Assets/Snippets/RewardedAdSnippets.cs#L40-L46\n\nReplace \u003cvar class=\"readonly\" translate=\"no\"\u003eSAMPLE_CUSTOM_DATA_STRING\u003c/var\u003e with your custom data.\n\nIf you want to set the custom reward string, you must do so before showing the\nad.\n| **Key Point:** The custom reward string is [percent\n| escaped](//en.wikipedia.org/wiki/Percent-encoding) and might require decoding when parsed from the SSV callback.\n\nShow the rewarded ad with reward callback\n\nWhen presenting your ad, you must provide a callback to handle the reward for\nthe user. Ads can only be shown once per load. Use the `CanShowAd()` method to\nverify that the ad is ready to be shown.\n\nThe following code presents the best method for displaying a rewarded ad. \n\n if (rewardedAd != null && rewardedAd.CanShowAd())\n {\n rewardedAd.Show((Reward reward) =\u003e\n {\n // The ad was showen and the user earned a reward.\n });\n } \n https://github.com/googleads/googleads-mobile-unity/blob/be5850e271b73dd450a89f44df67dac6b1f1712a/samples/HelloWorld/Assets/Snippets/RewardedAdSnippets.cs#L53-L59\n\nListen to rewarded ad events\n\nTo further customize the behavior of your ad, you can hook into a number of\nevents in the ad's lifecycle. The following code listens for ad events: \n\n rewardedAd.OnAdPaid += (AdValue adValue) =\u003e\n {\n // Raised when the ad is estimated to have earned money.\n };\n rewardedAd.OnAdImpressionRecorded += () =\u003e\n {\n // Raised when an impression is recorded for an ad.\n };\n rewardedAd.OnAdClicked += () =\u003e\n {\n // Raised when a click is recorded for an ad.\n };\n rewardedAd.OnAdFullScreenContentOpened += () =\u003e\n {\n // Raised when the ad opened full screen content.\n };\n rewardedAd.OnAdFullScreenContentClosed += () =\u003e\n {\n // Raised when the ad closed full screen content.\n };\n rewardedAd.OnAdFullScreenContentFailed += (AdError error) =\u003e\n {\n // Raised when the ad failed to open full screen content.\n }; \n https://github.com/googleads/googleads-mobile-unity/blob/be5850e271b73dd450a89f44df67dac6b1f1712a/samples/HelloWorld/Assets/Snippets/RewardedAdSnippets.cs#L66-L89\n\nClean up the rewarded ad\n\nWhen you are finished with a `RewardedAd`, make sure to call the `Destroy()`\nmethod before dropping your reference to it: \n\n if (rewardedAd != null)\n {\n rewardedAd.Destroy();\n } \n https://github.com/googleads/googleads-mobile-unity/blob/be5850e271b73dd450a89f44df67dac6b1f1712a/samples/HelloWorld/Assets/Snippets/RewardedAdSnippets.cs#L96-L99\n\nThis notifies the plugin that the object is no longer used and the memory it\noccupies can be reclaimed. Failure to call this method results in memory leaks.\n\nPreload the next rewarded ad\n\n`RewardedAd` is a one-time-use object. This means once a rewarded ad is shown,\nthe object can't be used again. To request another rewarded ad,\nyou'll need to create a new `RewardedAd` object.\n\nTo prepare a rewarded ad for the next impression opportunity, preload the\nrewarded ad once the `OnAdFullScreenContentClosed` or\n`OnAdFullScreenContentFailed` ad event is raised. \n\n rewardedAd.OnAdFullScreenContentClosed += () =\u003e\n {\n // Reload the ad so that we can show another as soon as possible.\n var adRequest = new AdRequest();\n RewardedAd.Load(\"\u003cvar translate=\"no\"\u003eAD_UNIT_ID\u003c/var\u003e\", adRequest, (RewardedAd ad, LoadAdError error) =\u003e\n {\n // Handle ad loading here.\n });\n }; \n https://github.com/googleads/googleads-mobile-unity/blob/be5850e271b73dd450a89f44df67dac6b1f1712a/samples/HelloWorld/Assets/Snippets/RewardedAdSnippets.cs#L106-L114\n\nAdditional resources\n\n- [HelloWorld example](//github.com/googleads/googleads-mobile-unity/tree/main/samples/HelloWorld): A minimal implementation of all ad formats."]]