# 4-3. 배너 광고 for Unity

## 사전 작업

{% content-ref url="/pages/E4sVveRS1O07LDkxrZrf" %}
[04. Unity-Plugin Guide](/one-admax-sdk/unityplugin.md)
{% endcontent-ref %}

## ONEAdMax SDK 초기화

광고를 로드하기 전 ONEAdMax 초기화가  필요하며, \
`ONEAdMaxClient.Initialize()` 는최초 한 번만 수행해야 합니다.

```csharp
...
using ONEAdMax;
...
public class ONEAdMaxDemo : MonoBehaviour
{
    private static bool _isInitialized = false;
    
    void Start()
    {
        if (!_isInitialized)
        {
            // Initialize the ONEAdMax SDK.
            ONEAdMaxClient.Initialize(() =>
            {
                // This callback is called once the ONEAdMax SDK is initialized.
                _isInitialized = true
            });
        }
    }
}
```

## Banner ADs Sample Code

`OAMBannerView` 인스턴스를 생성하고, 라이프사이클 이벤트를 처리하여 기능을 확장할 수 있습니다.

### 배너 뷰 인스턴스 생성하기

```csharp
using ONEAdMax;
...
public class BannerViewController : MonoBehaviour
{    
    OAMBannerView _bannerView;
    
    public void CreateBannerView()
    {
        Debug.Log("Creating banner view.");

        // If we already have a banner.
        if (_bannerView != null) {
            Debug.LogWarning("Already have a banner.");
            return;
        }

        // Create a 320x50 banner view at top of the screen.
        _bannerView = new OAMBannerView(AdSize.BANNER_320x50, AdPosition.Top);
    }
}
```

{% hint style="success" %}
배너 뷰 생성자의 매개변수

* `AdSize`: 사용하고자 하는 광고의 크기.
* `AdPosition`: 배너 뷰를 배치해야 하는 위치.
  {% endhint %}

### 배너 크기

<table><thead><tr><th>Size</th><th>상수(Constant)</th><th data-hidden>상수</th><th data-hidden></th></tr></thead><tbody><tr><td>320x50</td><td>AdSize.BANNER_320x50</td><td>BANNER_320x50</td><td></td></tr><tr><td>300x250</td><td>AdSize.BANNER_300x250</td><td>BANNER_300x250</td><td></td></tr><tr><td>320x100</td><td>AdSize.BANNER_320x100</td><td>BANNER_320x100</td><td></td></tr></tbody></table>

### 배너 노출 애니메이션 설정

배너가 노출될 때의 애니메이션을 설정합니다. (기본값: `AnimType.NONE`)\
총 7가지의 애니메이션을 설정할 수 있습니다.

```csharp
_bannerView.SetAnimType(AnimType.SLIDE_LEFT); // Defaults to AnimType.NONE
```

#### &#x20;애니메이션 타입 종류

<table><thead><tr><th width="261">상수</th><th>설명</th><th data-hidden>설명</th><th data-hidden></th></tr></thead><tbody><tr><td><code>AnimType.NONE</code></td><td>애니메이션 없음 (기본값) (No animation (default))</td><td></td><td></td></tr><tr><td><code>AnimType.FADE_IN</code></td><td>페이드 인 애니메이션(Fade-in animation)</td><td></td><td></td></tr><tr><td><code>AnimType.SLIDE_LEFT</code></td><td>왼쪽으로 슬라이드 애니메이션(Slide animation to the left)</td><td></td><td></td></tr><tr><td><code>AnimType.SLIDE_RIGHT</code></td><td>오른쪽으로 슬라이드 애니메이션(Slide animation to the right)</td><td></td><td></td></tr><tr><td><code>AnimType.TOP_SLIDE</code></td><td>위쪽으로 슬라이드 애니메이션(Slide animation from the top)</td><td></td><td></td></tr><tr><td><code>AnimType.BOTTOM_SLIDE</code></td><td>아래쪽으로 슬라이드 애니메이션(Slide animation from the bottom)</td><td></td><td></td></tr><tr><td><code>AnimType.CIRCLE</code></td><td>배너 회전 애니메이션(Banner rotation animation)</td><td></td><td></td></tr></tbody></table>

### 네트워크 스케줄 타임아웃 설정 (선택사항)

배너광고에 대한 네트워크 스케줄 타임아웃을 설정합니다. (기본값: 5초)\
광고 로딩 시 각 네트워크 별로 타임아웃 시간을 주어 해당 시간 안에 광고를 받지 못할 경우, 다음 네트워크로 넘어가게 됩니다.

```csharp
_bannerView.SetNetworkScheduleTimeout(5); // Default 5 seconds
```

### 배너 광고 요청 갱신주기 설정 (선택사항)

배너 광고에 대한 갱신주기를 설정합니다. (기본값: 60초)\
설정 가능 범위는 15 \~ 300초 사이이며 -1로 설정 시 자동으로 갱신되지 않습니다.

```csharp
// The default is 60 seconds, with a setting range of 15 to 300 seconds.
_bannerView.SetRefreshTime(60);
```

### 배너 배경색 채우기 (선택사항)

배너 뷰의 빈 공간에 배경색을 채울 수 있습니다. (기본값: true)

```csharp
_bannerView.SetAutoBgColor(true); // Defaults to true
```

### 배너 미디에이션 옵션 설정 (선택사항)

배너 광고의 일부 미디에이션에 대한 설정 값을 지원합니다.

```csharp
/// <summary>
/// Extend the functionality of the mediation that appears in your ads.
/// </summary>
/// <seealso cref="MediationKey" />
/// <param name="ad"><see cref="OAMBannerView"/></param>
private void SetMediationExtras(OAMBannerView ad)
{
    var extras = new Dictionary<MediationKey, object>
    {
        // Set to true to show Cauly ads on the lock screen. (Defaults to false)
        { MediationKey.CAULY_ENABLE_LOCK, false },
        
        // Control ad serving intervals on Cauly's side. (Defaults to true)
        { MediationKey.CAULY_ENABLE_DYNAMIC_RELOAD_INTERVAL, true },
        
        // Controls how often ads appear in media. (Default 20 seconds)
        // (available after changing CAULY_DAYNAMIC_RELOAD_INTERVAL to False)
        { MediationKey.CAULY_RELOAD_INTERVAL, 20 },
        
        // Set thread priority.
        { MediationKey.CAULY_THREAD_PRIORITY, 5 },
        
        // Options to set age information for meso ads. (Defaults to -1)
        // Unknown = -1; Children(under 13) = 0; Teens and adults(over 13) = 1
        { MediationKey.MEZZO_AGE_LEVEL, -1 },
        
        // Option to allow the banner to run in the background. (true | false)
        { MediationKey.MEZZO_ENABLE_BACKGROUND_CHECK, false },
        
        // The app's Store URL
        { MediationKey.MEZZO_STORE_URL, "..." }
    };

    ad.SetMediationExtras(extras);
}
```

{% content-ref url="/pages/VOLfvFGJr4AThR1gTLLM" %}
[미디에이션 설정 가이드](/one-admax-sdk/undefined.md)
{% endcontent-ref %}

### 배너 뷰의 이벤트 청취하기 (선택사항)

```csharp
/// <summary>
/// Register to events the banner may raise.
/// </summary>
private void RegisterEvents(OAMBannerView ad)
{
    // Raised when an ad is loaded into the banner view.
    ad.OnLoaded += () =>
    {
        Debug.Log("Banner view loaded.");
    };

    // Raised when an ad fails to load into the banner view.
    ad.OnLoadFailed += (OAMError error) =>
    {
        Debug.LogError("Banner view failed to load an ad with error : " + error);
    };

    // Raised when a click is recorded for an ad.
    ad.OnClicked += () =>
    {
        Debug.Log("Banner view was clicked.");
    };
}
```

{% content-ref url="/pages/i8O1iX5eJtrY4LjZBdFC" %}
[ONE AdMax SDK Error Codes](/one-admax-sdk/oamerror.md)
{% endcontent-ref %}

### 배너 뷰 생성하기

모든 설정을 완료하고 `OAMBannerView`를 생성합니다.

```csharp
// These ad units are configured to always serve test ads.   
private readonly string _placementId = "String your placementID";  // 320 * 50

_bannerView.Create(_placementId);
```

### 배너  광고 로드 하기

배너 광고 노출을 원하는 시점에 `Load()` API를 호출하여 서버에 광고를 요청합니다.

```csharp
/// <summary>
/// Creates the banner view and loads a banner ad.
/// </summary>
public void Load()
{
    if (_bannerView == null)
    {
        Debug.LogWarning("The banner view is null.");
        return;
    }

    _bannerView.Load();
}
```

{% hint style="warning" %}
과도한 광고 요청은 차단 사유가 되니 주의해주세요!
{% endhint %}

### 배너 광고 노출 중단하기

배너 광고 노출을 더 이상 원하지 않는 시점에 호출합니다.

```csharp
/// <summary>
/// Destroys the ad.
/// When you are finished with a OAMBannerView, make sure to call
/// the Destroy() method before dropping your reference to it.
/// </summary>
public void Destroy()
{
    if (_bannerView != null)
    {
        Debug.Log("Destroying banner view.");
        _bannerView.Destroy();
        _bannerView = null;
    }
}
```

{% hint style="danger" %}
단, 어플리케이션이 Pause 상태일 경우 Destroy()를 호출할 경우 클릭 리포트가 누락되는 경우가  발생  될 수 있으므로 배너 뷰가 포함된 Activity 또는 Fragment가 destroy 될 때 호출해야 합니다.
{% endhint %}

### 배너 광고 로드 여부 체크하기

배너 광고의 로드 여부를 체크합니다. (return ture | false)

```csharp
_bannerView.IsLoaded();
```

### 어플리케이션의 라이프사이클 확장하기

배너 광고가 노출되고 있는 어플리케이션의 `onPause` / `onResume`여부를 체크하기 위해 구현합니다.

```csharp
public class BannerViewController : MonoBehaviour
{
    void OnApplicationPause(bool pauseStatus)
    {
        // You should call events for pause and resume in the application lifecycle.
        _bannerView?.OnPause(pauseStatus);
    }
}
```

{% hint style="warning" %}

#### 주의사항

미 처리 시,  third-party mediation 사용에서 리포트 수치가 누락되는 경우가 발생합니다.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://one-admax-organization.gitbook.io/one-admax-sdk/unityplugin/banner.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
