배너 광고

배너 보기는 화면 안의 한 지점을 차지하는 직사각형 이미지 또는 텍스트 광고입니다. 사용자가 앱과 상호작용하는 동안 화면에 머무르며 일정 시간이 지나면 자동으로 새로고침할 수 있습니다. 모바일 광고를 처음 시작하는 경우 배너 광고를 이용하는 것이 좋습니다.

이 가이드에서는 배너 보기를 Unity 앱에 통합하는 방법을 설명합니다. 코드 스니펫과 안내 외에도 배너 크기 조정에 대한 정보와 추가 리소스에 대한 링크가 포함되어 있습니다.

기본 요건

항상 테스트 광고로 테스트

다음 샘플 코드에는 테스트 광고를 요청하는 데 사용할 수 있는 광고 단위 ID가 포함되어 있습니다. 이 ID는 모든 요청에 대해 프로덕션 광고가 아닌 테스트 광고를 반환하도록 구성되어서 안전하게 사용할 수 있습니다.

그러나Ad Manager 웹 인터페이스에 앱을 등록하고 앱에서 사용할 광고 단위 ID를 직접 만든 후에는 개발 중에 명시적으로 기기를 테스트 기기로 구성해야 합니다.

/6499/example/banner

모바일 광고 SDK 초기화

광고를 로드하기 전에 MobileAds.Initialize()를 호출하여 앱에서 모바일 광고 SDK를 초기화하도록 합니다. 이 작업은 앱 실행 시 한 번만 처리하면 됩니다.

using GoogleMobileAds;
using GoogleMobileAds.Api;

public class GoogleMobileAdsDemoScript : MonoBehaviour
{
    public void Start()
    {
        // Initialize the Google Mobile Ads SDK.
        MobileAds.Initialize((InitializationStatus initStatus) =>
        {
            // This callback is called once the MobileAds SDK is initialized.
        });
    }
}

미디에이션을 사용하는 경우 광고를 로드하기 전에 콜백이 발생할 때까지 기다려야 모든 미디에이션 어댑터가 초기화됩니다.

BannerView 예시

아래의 샘플 코드에는 배너 보기를 사용하는 방법이 자세히 나와 있습니다. 이 예에서는 배너 보기의 인스턴스를 만들고 AdManagerAdRequest를 사용하여 광고를 배너 보기에 로드한 다음 수명 주기 이벤트를 처리하여 기능을 확장합니다.

배너 보기 만들기

배너 보기 사용의 첫 번째 단계는 GameObject에 첨부된 C# 스크립트에서 배너 보기의 인스턴스를 만드는 것입니다.


  // This ad unit is configured to always serve test ads.
  private string _adUnitId = "/6499/example/banner";

  AdManagerBannerView _bannerView;

  /// <summary>
  /// Creates a 320x50 banner view at top of the screen.
  /// </summary>
  public void CreateBannerView()
  {
      Debug.Log("Creating banner view");

      // If we already have a banner, destroy the old one.
      if (_bannerView != null)
      {
          DestroyAd();
      }

      // Create a 320x50 banner at top of the screen
      _bannerView = new AdManagerBannerView(_adUnitId, AdSize.Banner, AdPosition.Top);
  }

AdManagerBannerView의 생성자에는 다음과 같은 매개변수가 있습니다.

  • adUnitId: AdManagerBannerView가 광고를 로드하는 광고 단위 ID입니다.
  • AdSize: 사용할 광고 크기입니다. 자세한 내용은 배너 크기를 참고하세요.
  • AdPosition: 배너 보기를 배치할 위치입니다. AdPosition enum은 유효한 광고 게재순위 값을 나열합니다.

플랫폼에 따라 다른 광고 단위가 사용됩니다. iOS에서 광고 요청을 하려면 iOS 광고 단위를 사용하고 Android에서 광고 요청을 하려면 Android 광고 단위를 사용해야 합니다.

(선택사항) 맞춤 위치로 배너 보기 만들기

화면에서 AdManagerBannerView의 위치를 AdPosition의 값보다 더욱 세부적으로 지정하려면 x 좌표 및 y 좌표를 매개변수로 갖는 생성자를 사용하세요.

// Create a 320x50 banner views at coordinate (0,50) on screen.
_bannerView = new AdManagerBannerView(_adUnitId, AdSize.Banner, 0, 50);

AdManagerBannerView의 왼쪽 상단 모서리는 생성자에 전달된 x 및 y 값에 배치됩니다. 여기에서 원점은 화면의 왼쪽 상단입니다.

(선택사항) 맞춤 크기로 배너 보기 만들기

AdSize 상수를 사용하는 것 외에도 광고에 맞춤 크기를 지정할 수 있습니다.

// Use the AdSize argument to set a custom size for the ad.
AdSize adSize = new AdSize(250, 250);
_bannerView = new AdManagerBannerView(_adUnitId, adSize, AdPosition.Bottom);

(선택사항) 여러 광고 크기

Ad Manager를 사용하면 AdManagerBannerView에 게재할 수 있는 여러 광고 크기를 지정할 수 있습니다. SDK에서 이 기능을 구현하기 전에 동일한 광고 단위를 타겟팅하는 광고 항목을 만들어 크기가 다른 광고 소재와 연결되어 있어야 합니다.

앱에서 여러 AdSize 매개변수를 ValidAdSizes에 전달합니다.

var adView = new AdManagerBannerView(_adUnitId, AdSize.Banner, AdPosition.Top);
adView.ValidAdSizes = new List<AdSize>
{
    AdSize.Banner, new AdSize(120, 20), new AdSize(250, 250),
};

새로고침 시 AdManagerAdView에서 크기가 변경되면 레이아웃이 자동으로 새 크기에 맞게 조정될 수 있어야 합니다. AdManagerAdView는 다음 광고가 반환될 때까지 첫 번째 매개변수에 전달되는 크기로 기본 설정됩니다.

배너 광고 로드

AdManagerBannerView가 지정되면 AdManagerBannerView 클래스의 LoadAd() 메서드를 이용해 광고를 로드하세요. 타겟팅 정보, 제외 라벨, 게시자 제공 ID와 같은 런타임 정보를 보유하는 AdManagerAdRequest 매개변수를 사용합니다.

/// <summary>
/// Creates the banner view and loads a banner ad.
/// </summary>
public void LoadAd()
{
    // create an instance of a banner view first.
    if(_bannerView == null)
    {
        CreateAdManagerBannerView();
    }

    // create our request used to load the ad.
    var adRequest = new AdManagerAdRequest();

    // send the request to load the ad.
    Debug.Log("Loading banner ad.");
    _bannerView.LoadAd(adRequest);
}

배너 보기 이벤트 수신

광고의 작동 방식을 맞춤설정하기 위해 광고의 수명 주기에서 여러 이벤트(예: 로드, 열기, 닫기)에 연결하면 됩니다. 이러한 이벤트를 수신하려면 대리자를 등록하세요.

/// <summary>
/// listen to events the banner view may raise.
/// </summary>
private void ListenToAdEvents()
{
    // Raised when an ad is loaded into the banner view.
    _bannerView.OnBannerAdLoaded += () =>
    {
        Debug.Log("Banner view loaded an ad with response : "
            + _bannerView.GetResponseInfo());
    };
    // Raised when an ad fails to load into the banner view.
    _bannerView.OnBannerAdLoadFailed += (LoadAdError error) =>
    {
        Debug.LogError("Banner view failed to load an ad with error : "
            + error);
    };
    // Raised when the ad is estimated to have earned money.
    _bannerView.OnAdPaid += (AdValue adValue) =>
    {
        Debug.Log(String.Format("Banner view paid {0} {1}.",
            adValue.Value,
            adValue.CurrencyCode));
    };
    // Raised when an impression is recorded for an ad.
    _bannerView.OnAdImpressionRecorded += () =>
    {
        Debug.Log("Banner view recorded an impression.");
    };
    // Raised when a click is recorded for an ad.
    _bannerView.OnAdClicked += () =>
    {
        Debug.Log("Banner view was clicked.");
    };
    // Raised when an ad opened full screen content.
    _bannerView.OnAdFullScreenContentOpened += () =>
    {
        Debug.Log("Banner view full screen content opened.");
    };
    // Raised when the ad closed full screen content.
    _bannerView.OnAdFullScreenContentClosed += () =>
    {
        Debug.Log("Banner view full screen content closed.");
    };
}

배너 보기 소멸

배너 보기 사용을 마치면 Destroy()를 호출하여 리소스를 해제해야 합니다.

/// <summary>
/// Destroys the banner view.
/// </summary>
public void DestroyBannerView()
{
    if (_bannerView != null)
    {
        Debug.Log("Destroying banner view.");
        _bannerView.Destroy();
        _bannerView = null;
    }
}

작업이 끝났습니다. 이제 앱에서 배너 광고를 게재할 수 있습니다.

아래 표에는 표준 배너 크기가 나와 있습니다.

크기(dp)(WxH) 설명 지원 대상 AdSize 상수
320x50 표준 배너 휴대전화 및 태블릿 BANNER
320x100 대형 배너 휴대전화 및 태블릿 LARGE_BANNER
300x250 IAB 중간 직사각형 휴대전화 및 태블릿 MEDIUM_RECTANGLE
468 x 60 IAB 원본 크기 배너 태블릿 FULL_BANNER
728x90 IAB 리더보드 태블릿 LEADERBOARD
제공된 너비x적응형 높이 적응형 배너 휴대전화 및 태블릿 해당 사항 없음
화면 너비x32|50|90 스마트 배너 휴대전화 및 태블릿 SMART_BANNER
스마트 배너 대신 사용할 수 있는 적응형 배너에 대해 자세히 알아보세요.

앱 이벤트

앱 이벤트를 사용하면 앱 코드에 메시지를 전송하는 광고를 만들 수 있습니다. 그러면 앱에서 이러한 메시지를 기반으로 작업을 수행할 수 있습니다.

AppEvent를 사용하여 Ad Manager 관련 앱 이벤트를 수신할 수 있습니다. 이러한 이벤트는 로드가 호출되기 전을 포함해 광고의 수명 주기 동안 언제든지 발생할 수 있습니다.

namespace GoogleMobileAds.Api.AdManager;

/// The App event message sent from the ad.
public class AppEvent
{
    // Name of the app event.
    string Name;
    // Argument passed from the app event.
    string Value;
}

OnAppEventReceived는 광고에서 앱 이벤트가 발생하면 발생합니다. 다음은 코드에서 이 이벤트를 처리하는 방법을 보여주는 예입니다.

_bannerview.OnAppEventReceived += (AppEvent args) =>
{
    Debug.Log($"Received app event from the ad: {args.Name}, {args.Value}.");
};

다음은 색상 이름이 적용된 앱 이벤트에 따라 앱의 배경색을 변경하는 방법의 예입니다.

_bannerview.OnAppEventReceived += (AppEvent args) =>
{
  if (args.Name == "color")
  {
    Color color;
    if (ColorUtility.TryParseColor(arg.Value, out color))
    {
      gameObject.GetComponent<Renderer>().material.color = color;
    }
  }
};

다음은 색상 앱 이벤트를 전송하는 해당 광고 소재입니다.

<html>
<head>
  <script src="//www.gstatic.com/afma/api/v1/google_mobile_app_ads.js"></script>
  <script>
    document.addEventListener("DOMContentLoaded", function() {
      // Send a color=green event when ad loads.
      admob.events.dispatchAppEvent("color", "green");

      document.getElementById("ad").addEventListener("click", function() {
        // Send a color=blue event when ad is clicked.
        admob.events.dispatchAppEvent("color", "blue");
      });
    });
  </script>
  <style>
    #ad {
      width: 320px;
      height: 50px;
      top: 0px;
      left: 0px;
      font-size: 24pt;
      font-weight: bold;
      position: absolute;
      background: black;
      color: white;
      text-align: center;
    }
  </style>
</head>
<body>
  <div id="ad">Carpe diem!</div>
</body>
</html>

추가 리소스