보상형 전면 광고는 자연스러운 앱 전환 중에 자동으로 게재되는 광고에 대해 보상을 제공하는 인센티브형 광고 형식입니다. 보상형 광고와 달리 사용자는 수신 동의를 하지 않고도 보상형 전면 광고를 볼 수 있습니다.
기본 요건
- 시작 가이드에 따라 필요한 과정을 완료합니다.
항상 테스트 광고로 테스트합니다
아래 샘플 코드에는 테스트 광고 요청에 사용할 수 있는 광고 단위 ID가 포함되어 있습니다. 이 ID는 모든 요청에 대해 실제 광고가 아닌 테스트 광고를 반환하도록 구성되어서 안전하게 사용할 수 있습니다.
그러나 AdMob 웹 인터페이스에 앱을 등록하고 앱에서 사용할 광고 단위 ID를 직접 생성한 후에는 개발 중에 명확하게 기기를 테스트 기기로 설정하세요.
Android
ca-app-pub-3940256099942544/5354046379
iOS
ca-app-pub-3940256099942544/6978759866
모바일 광고 SDK 초기화
광고를 로드하기 전에 앱에서 MobileAds.Initialize()를 호출하여 Google 모바일 광고 SDK를 초기화합니다. 이 작업은 앱 실행 시 한 번만 처리하면 됩니다.
using GoogleMobileAds;
using GoogleMobileAds.Api;
public class GoogleMobileAdsDemoScript : MonoBehaviour
{
    public void Start()
    {
        // Initialize Google Mobile Ads SDK.
        MobileAds.Initialize((InitializationStatus initStatus) =>
        {
            // This callback is called once the MobileAds SDK is initialized.
        });
    }
}
미디에이션을 사용하는 경우 광고 로드 전에 콜백이 발생할 때까지 기다려야 모든 미디에이션 어댑터가 초기화됩니다.
구현
보상형 전면 광고를 통합하는 기본 단계는 아래와 같습니다.
- 보상형 전면 광고 로드
- [선택사항] 서버 측 확인(SSV) 콜백 검사
- 리워드 콜백으로 보상형 전면 광고 표시
- 보상형 전면 광고 이벤트 수신 대기
- 보상형 전면 광고 정리
- 다음 보상형 전면 광고 미리 로드
보상형 전면 광고 로드
보상형 전면 광고는 RewardedInterstitialAd 클래스의 정적 Load() 메서드를 사용하여 로드됩니다. 로드 메서드에는 광고 단위 ID, AdRequest 객체, 광고 로드에 성공하거나 실패할 때 호출되는 완료 핸들러가 필요합니다. 로드된 RewardedInterstitialAd 객체는 완료 핸들러의 매개변수로 제공됩니다. 아래는 RewardedInterstitialAd를 로드하는 방법의 예입니다.
  // These ad units are configured to always serve test ads.
#if UNITY_ANDROID
  private string _adUnitId = "ca-app-pub-3940256099942544/5354046379";
#elif UNITY_IPHONE
  private string _adUnitId = "ca-app-pub-3940256099942544/6978759866";
#else
  private string _adUnitId = "unused";
#endif
  private RewardedInterstitialAd _rewardedInterstitialAd;
  /// <summary>
  /// Loads the rewarded interstitial ad.
  /// </summary>
  public void LoadRewardedInterstitialAd()
  {
      // Clean up the old ad before loading a new one.
      if (_rewardedInterstitialAd != null)
      {
            _rewardedInterstitialAd.Destroy();
            _rewardedInterstitialAd = null;
      }
      Debug.Log("Loading the rewarded interstitial ad.");
      // create our request used to load the ad.
      var adRequest = new AdRequest();
      adRequest.Keywords.Add("unity-admob-sample");
      // send the request to load the ad.
      RewardedInterstitialAd.Load(_adUnitId, adRequest,
          (RewardedInterstitialAd ad, LoadAdError error) =>
          {
              // if error is not null, the load request failed.
              if (error != null || ad == null)
              {
                  Debug.LogError("rewarded interstitial ad failed to load an ad " +
                                 "with error : " + error);
                  return;
              }
              Debug.Log("Rewarded interstitial ad loaded with response : "
                        + ad.GetResponseInfo());
              _rewardedInterstitialAd = ad;
          });
  }
[선택사항] 서버 측 확인(SSV) 콜백 검사
서버 측 확인 콜백에서 추가 데이터가 필요한 앱은 보상형 광고의 맞춤 데이터 기능을 사용해야 합니다.
보상형 광고 객체에 설정된 모든 문자열 값은 SSV 콜백의 custom_data 쿼리 매개변수에 전달됩니다. 맞춤 데이터 값이 설정되지 않은 경우
custom_data 쿼리 매개변수 값은 SSV 콜백에 포함되지 않습니다.
다음 코드 샘플은 보상형 전면 광고가 로드된 후 SSV 옵션을 설정하는 방법을 보여줍니다.
// send the request to load the ad.
RewardedInterstitialAd.Load(_adUnitId,
                            adRequest,
                            (RewardedInterstitialAd ad, LoadAdError error) =>
    {
        // If the operation failed, an error is returned.
        if (error != null || ad == null)
        {
            Debug.LogError("Rewarded interstitial ad failed to load an ad " +
                           " with error : " + error);
            return;
        }
        // If the operation completed successfully, no error is returned.
        Debug.Log("Rewarded interstitial ad loaded with response : " +
                   ad.GetResponseInfo());
        
        // Create and pass the SSV options to the rewarded ad.
        var options = new ServerSideVerificationOptions
                              .Builder()
                              .SetCustomData("SAMPLE_CUSTOM_DATA_STRING")
                              .Build()
        ad.SetServerSideVerificationOptions(options);
        
});
맞춤 보상 문자열을 설정하려면 광고를 게재하기 전에 해야 합니다.
리워드 콜백으로 보상형 전면 광고 표시
광고를 표시할 때 사용자의 보상을 처리할 콜백을 제공해야 합니다. 광고는 로드당 한 번만 게재될 수 있습니다. CanShowAd() 메서드를 사용하여 광고를 게재할 준비가 되었다는 것을 확인하세요.
다음 코드는 보상형 전면 광고를 게재하기 위한 최적의 메서드를 나타냅니다.
public void ShowRewardedInterstitialAd()
{
    const string rewardMsg =
        "Rewarded interstitial ad rewarded the user. Type: {0}, amount: {1}.";
    if (rewardedInterstitialAd != null && rewardedInterstitialAd.CanShowAd())
    {
        rewardedInterstitialAd.Show((Reward reward) =>
        {
            // TODO: Reward the user.
            Debug.Log(String.Format(rewardMsg, reward.Type, reward.Amount));
        });
    }
}
보상형 전면 광고 이벤트 수신 대기
광고의 작동 방식을 더 세부적으로 맞춤설정하려는 경우 광고의 수명 주기에서 여러 이벤트에 연결하면 됩니다. 아래와 같이 대리자를 등록하여 이러한 이벤트를 수신 대기합니다.
private void RegisterEventHandlers(RewardedInterstitialAd ad)
{
    // Raised when the ad is estimated to have earned money.
    ad.OnAdPaid += (AdValue adValue) =>
    {
        Debug.Log(String.Format("Rewarded interstitial ad paid {0} {1}.",
            adValue.Value,
            adValue.CurrencyCode));
    };
    // Raised when an impression is recorded for an ad.
    ad.OnAdImpressionRecorded += () =>
    {
        Debug.Log("Rewarded interstitial ad recorded an impression.");
    };
    // Raised when a click is recorded for an ad.
    ad.OnAdClicked += () =>
    {
        Debug.Log("Rewarded interstitial ad was clicked.");
    };
    // Raised when an ad opened full screen content.
    ad.OnAdFullScreenContentOpened += () =>
    {
        Debug.Log("Rewarded interstitial ad full screen content opened.");
    };
    // Raised when the ad closed full screen content.
    ad.OnAdFullScreenContentClosed += () =>
    {
        Debug.Log("Rewarded interstitial ad full screen content closed.");
    };
    // Raised when the ad failed to open full screen content.
    ad.OnAdFullScreenContentFailed += (AdError error) =>
    {
        Debug.LogError("Rewarded interstitial ad failed to open " +
                       "full screen content with error : " + error);
    };
}
보상형 전면 광고 정리
RewardedInterstitialAd 사용이 끝나면 참조를 삭제하기 전에 Destroy() 메서드를 호출해야 합니다.
_rewardedInterstitialAd.Destroy();
이렇게 하면 객체가 더 이상 사용되지 않는다는 것을 플러그인에게 알려 객체가 사용한 메모리를 복구할 수 있습니다. 이 메서드를 호출하지 않으면 메모리 누수가 발생합니다.
다음 보상형 전면 광고 미리 로드
RewardedInterstitialAd는 일회용 객체입니다. 즉, 보상형 전면 광고가 표시된 후에는 이 객체를 다시 사용할 수 없습니다. 보상형 전면 광고를 추가로 요청하려면 새 RewardedInterstitialAd 객체를 로드해야 합니다.
다음 노출 기회에 보상형 전면 광고가 게재되도록 OnAdFullScreenContentClosed 또는 OnAdFullScreenContentFailed 광고 이벤트가 발생한 후에 보상형 전면 광고를 미리 로드합니다.
private void RegisterReloadHandler(RewardedInterstitialAd ad)
{
    // Raised when the ad closed full screen content.
    ad.OnAdFullScreenContentClosed += ()
    {
        Debug.Log("Rewarded interstitial ad full screen content closed.");
        // Reload the ad so that we can show another as soon as possible.
        LoadRewardedInterstitialAd();
    };
    // Raised when the ad failed to open full screen content.
    ad.OnAdFullScreenContentFailed += (AdError error) =>
    {
        Debug.LogError("Rewarded interstitial ad failed to open " +
                       "full screen content with error : " + error);
        // Reload the ad so that we can show another as soon as possible.
        LoadRewardedInterstitialAd();
    };
}
추가 리소스
- HelloWorld 예시: 모든 광고 형식의 최소 구현입니다.