Advertisement Legacy 구현
사용된 유니티 버전은 2022.3.32f1 이며 Advertisement Legacy 4.4.2 · April 03, 2023 버전을 사용한다.
본 글에서는 연동하는 방법에 대해서는 다루지 않는다.특별히 요구되는 부분은 많지 않다. 유니티에서 제공하는 간단한 예제를 사용하면 쉽게 유니티 광고를 프로젝트에 연결할 수 있다. 문제가 발생할 수 있는 부분만 설명한다.
아래의 링크를 참조한다.
2024.07.01 - [유니티/중급] - Unity Ads - Monetization 연동
Unity Ads - Monetization 연동
1. Unity Dashboard. 유니티 대시보드의 Unity Ads - Monetization을 설정한다. https://cloud.unity.com/home/login Unity Cloud cloud.unity.com 2. Advertisement legacy 패키지 설치 유니티 Advertisement legacy를 설치한다. 위치
notyu.tistory.com
1. Unity.Advertisements namespace
Advertisement Legacy와 관련된 클래스는 Unity.Advertisements 네임스페이스에 있다.
네임스페이스는 관련된 요소들을 포함하는 범위를 선언하는 데 사용하며, 관련된 클래스, 인터페이스 등을 사용하기 위해서는 선언을 해주어야 한다 [1].
Using Unity.Advertisements;
2. gameId
우선 프로젝트를 유니티 광고와 연결한다.
광고와 연결하기 위해서는 Unity Ads Monetization의 식별자가 필요하다. 식별자는 Game ID이다.
Unity Ads Monetization에서 자신이 연결하려고 하는 타겟 플랫폼의 gameId를 가져온다.
Unity Ads는 App store와 Andriod Store 두 개의 Game ID가 있다.
위치는 아래와 같다.
- Unity Ads Monetization → Settings → Game IDs
3. 초기화 및 연결
3.1. Advertisement.Initialize(string, bool, Interface)
유니티 광고 서버 접속은 Advertisement의 Initialize를 사용하면 된다. Insitialize를 통해 유니티 광고 서버에 성공적으로 접속을 하면, Scene을 변경할 때마다 Initialize를 할 필요는 없다. 앱이 종료할 때까지 계속 반복적으로 호출하지 않아도 접속은 유지된다.
- 유니티 프로젝트를 테스트할 경우에는 testMode를 true로 설정한다.
- 앱을 배포할 때에는 testMode = false로 설정한다.
Advertisement.Initialize(string _gameId, bool testMode, IUnityAdsIntaliationLister interface);
전처리 지시문을 사용하여 안드로이드 스토어, 애플 스토어에 맞는 GameID를 설정한다.
#if UNITY_IOS
_gameId = _iOSGameId;
#elif UNITY_ANDROID
_gameId = _androidGameId;
3.2. IUnityAdsInitializationListener
유니티 광고 서버에 접속이 정상적으로 되었는지 확인하는 인터페이스를 구현한다.
유니티 광고 서버에 접속이 완료 후에 필요한 행동이 있다면, void OnInitializationComplete()에서 처리하는 로직을 구현한다.
using UnityEngine.Advertisements;
public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener
{
public void OnInitializationComplete()
{
Debug.Log("Unity Ads initialization complete.");
// Do something
}
public void OnInitializationFailed(UnityAdsInitializationError error, string message)
{
Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
}
}
3.3. AdsInitializer Full Script [2]
게임오브젝트의 AdsInitializer를 등록하고 GameId를 추가한다.
using UnityEngine;
using UnityEngine.Advertisements;
public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener
{
[SerializeField] string _androidGameId;
[SerializeField] string _iOSGameId;
[SerializeField] bool _testMode = true;
private string _gameId;
void Awake()
{
InitializeAds();
}
public void InitializeAds()
{
#if UNITY_IOS
_gameId = _iOSGameId;
#elif UNITY_ANDROID
_gameId = _androidGameId;
#elif UNITY_EDITOR
_gameId = _androidGameId; //Only for testing the functionality in the Editor
#endif
if (!Advertisement.isInitialized && Advertisement.isSupported)
{
Advertisement.Initialize(_gameId, _testMode, this);
}
}
public void OnInitializationComplete()
{
Debug.Log("Unity Ads initialization complete.");
}
public void OnInitializationFailed(UnityAdsInitializationError error, string message)
{
Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
}
}
4. Advertisement Legacy 광고 재생 과정
Advertisement Legacy에서 광고가 재생되기 위한 과정은 다음과 같은 흐름으로 동일하다.
- Load : 서버에 요청해 광고를 로드한다.
- Show : 사용자의 입력을 받아 사용자에게 광고를 재생한다.
- Reward : 정상적으로 광고의 재생이 완료되면 보상을 제공한다.
5. Unity Ads Monetiaztion UnitID
Unity Ads Monetiaztion의 UnitID를 사용하여, 어떠한 종류의 광고를 재생할 것인지를 구분한다. UnitID는 대상 디바이스가 다르면, 다른 값을 가진다. UnitID는 추가 밎 수정이 가능하다.
기본 설정된 UnitId는 아래와 같다. Android와 iOS에서 요구하는 UnitID는 다르다.
- Interstitial : Interstitial_Android , Interstitial_iOS
- Rewarded : Rewarded_Android, Rewarded_iOS
- Banner : Banner_Android, Banner_iOS
6. Rewarded Ad 그리고 Interstitial Ad
InterstitialAd와 RewardedAd는 UnitID만 다르며, 동작하는 방식은 동일하다. 본 글에서는 RewardedAd에 대해서만 예제 코드를 제공한다.
- InterstitialAd는 유니티 Dashboard의 Unity Ads Monetization의 Interstitial UnitID를 등록한다.
- RewardedAd는 유니티 Dashboard의 Unity Ads Monetization의 Rewarded Ad의 UnitID를 등록한다.
UnitID의 위치는 아래와 같다.
- Unity Ads Monetization → Ad units
전처리 지시문을 사용하여 안드로이드 스토어, 애플 스토어에 맞는 UnitID를 설정한다.
#if UNITY_IOS
_adUnitId = _iOSAdUnitId;
#elif UNITY_ANDROID
_adUnitId = _androidAdUnitId;
#endif
6.1. Advertisement.Load()
보상형 유니티 광고를 보여주기 전에, 광고를 로드한다.
Load가 정상적으로 완료가 되면, 광고가 재생가능한 상태가 된다. 광고가 재생 가능한지 상태인지 확인 및 이에 대한 처리는 IUnityAdsLoadListener 인터페이스를 등록하여 구현한다.
6.2. Advertisement.Show()
광고가 로드되었으면, 버튼을 활성화한다. 사용자 입력을 받아, 광고를 보여준다.
6.3. Reward
사용자가 광고를 시청하였는지에 대해서는 IUnityAdsShowListener interface를 등록하여 확인한다.
광고가 완료되어, 사용자에게 광고 시청에 대한 보상을 지급하는 로직을 구성한다.
public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
{
if (adUnitId.Equals(_adUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
{
// Grant a reward.
}
}
6.4. RewardedAds 클래스 [2]
6.4.1. UnityAction 클래스
UnityAction 클래스는 여러개의 함수를 호출 할 수 있도록 제작된 클래스이다.
UnityAction 클래스를 사용하기 위해서는 nameSpace를 추가해야한다.
using UnityEngine.Events;
클래스 멤버 변수처럼 변수 생성 및 파라미터로 사용한다.
using UnityEngine.Events;
public class MyAction : MonoBehaviour
{
UnityAction<bool> onLoadCallback;
void LoadAds(UnityAction<bool> _onLoadCallback)
{
onLoadCallback = _onLoadCallback;
}
}
UnityAction에 등록된 함수를 Invoke()함수를 사용하여 호출한다.
null 조건부 연산자( ?. ) 는 null인지 아닌지 판단한다.
using UnityEngine.Events;
public class MyAction : MonoBehaviour
{
UnityAction<bool> onLoadCallback;
void LoadAds(UnityAction<bool> _onLoadCallback)
{
onLoadCallback = _onLoadCallback;
}
void CompeleteLoad()
{
onLoadCallback?.Invoke();
}
}
6.4.2. 광고 로드
광고가 로드가 이루어졌는지 확인하기 위해 UnityAction을 사용하여, 로드에 대한 결과 값을 리턴하도록 구현한다.
광고가 로드가 완료되면 버튼을 활성화하여, 사용자가 광고를 재생하도록 구현한다. 실패할 경우 다른 행동을 취하도록 한다.
6.4.3. 광고 재생
사용자가 광고를 재생하고 시청을 완료하면 보상을 제공하기 위해 UnityAction을 등록하여 결과를 리턴받도록 한다.
UnityAction onShowCallback;
6.4.4 RewardManager
RewardManager는 RewardedAd 클래스에 연결하여 사용자에게 광고의 보상을 제공하는 클래스이다. 광고를 로드하고, 광고를 보여주기 등을 컨트롤한다.
using UnityEngine;
using UnityEngine.UI;
public class RewardedAdManager : MonoBehaviour
{
public RewardedAd rewardedAd;
public Button adsButton;
// Awake is called once
void Awake()
{
adsButton.onClick.AddListener(OnAdsButtonClicked);
}
void OnLoadCallback(bool _isLoad)
{
if(_isLoad)
{
// Do something if success.
adsButton.enabled = true;
return;
}
// Do something when failed
}
void OnShowCallback(bool _isShow)
{
if(_isShow)
{
// Do something if success
return;
}
// Do something when failed
}
void OnAdsButtonClicked()
{
rewardedAd.ShowAd(OnShowCallback);
}
void OnCloseButtonClicked()
{
gameObject.SetActive(false);
}
public void DisplayRewardUI()
{
gameObject.SetActive(true);
adsButton.enabled = false;
rewardedAd.LoadAd(OnLoadCallback);
}
}
6.4.5. RewardedAd 클래스
using UnityEngine;
using UnityEngine.Advertisements;
using UnityEngine.Events;
public class RewardedAd : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
[SerializeField] string _androidAdUnitId = "Rewarded_Android";
[SerializeField] string _iOSAdUnitId = "Rewarded_iOS";
string _adUnitId = null; // This will remain null for unsupported platforms
UnityAction<bool> onLoadCallback;
UnityAction<bool> onShowCallback;
// Awake Called once
void Awake()
{
// Get the Ad Unit ID for the current platform:
#if UNITY_IOS
_adUnitId = _iOSAdUnitId;
#elif UNITY_ANDROID
_adUnitId = _androidAdUnitId;
#endif
}
// Call this public method when you want to get an ad ready to show.
public void LoadAd(UnityAction<bool> _onLoadCallback)
{
// IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
Debug.Log("Loading Ad: " + _adUnitId);
// Add LoadCallback
onLoadCallback = _onLoadCallback;
Advertisement.Load(_adUnitId, this);
}
// If the ad successfully loads, add a listener to the button and enable it:
public void OnUnityAdsAdLoaded(string adUnitId)
{
Debug.Log("Ad Loaded: " + adUnitId);
if (adUnitId.Equals(_adUnitId))
{
// Configure the button to call the ShowAd() method when clicked:
// Invoke LoadCallback
onLoadCallback?.Invoke(true);
onLoadCallback = null;
}
}
// Implement a method to execute when the user clicks the button:
public void ShowAd(UnityAction<bool> _onShowCallback)
{
// Add ShowCallback
onShowCallback = _onShowCallback;
// Then show the ad:
Advertisement.Show(_adUnitId, this);
}
// Implement the Show Listener's OnUnityAdsShowComplete callback method to determine if the user gets a reward:
public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
{
if (adUnitId.Equals(_adUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
{
Debug.Log("Unity Ads Rewarded Ad Completed");
// Grant a reward.
// Invoke ShowCallback
onShowCallback?.Invoke(true);
onShowCallback =null;
}
}
// Implement Load and Show Listener error callbacks:
public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
{
Debug.Log($"Error loading Ad Unit {adUnitId}: {error.ToString()} - {message}");
// Use the error details to determine whether to try to load another ad.
}
public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
{
Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
// Use the error details to determine whether to try to load another ad.
}
public void OnUnityAdsShowStart(string adUnitId) { }
public void OnUnityAdsShowClick(string adUnitId) { }
}
7. Banner Ad
배너 광고의 UnitID를 등록한다.
위치는 아래와 같다.
- Unity Ads Monetization → Ad units
7. 1. BannerPosition
7.1.1. Advertisement.Banner.SetPosition(BannerPosition)
SetPosition() 함수를 사용해 배너의 위치를 지정한다. 열거형을 사용하여, 배너의 위치를 설정한다.
Advertisement.Banner.SetPosition (BannerPosition.TOP_CENTER);
7.1.1. 열거형 BannerPosition
- BannerPosition.CENTER
- BannerPosition.TOP_CENTER
- BannerPosition.TOP_LEFT
- BannerPosition.TOP_RIGHT
- BannerPosition.BOTTOM_CENTER
- BannerPosition.BOTTOM_LEFT
- BannerPosition.BOTTOM_RIGHT
7.2. Advertisement.Banner.Load(string UnitId, BannerLoadOptions bannerLoadOptions)
배너를 로드한다. BannerLoadOptions class를 사용해 로드가 정상적으로 이루어졌는지 확인하는 콜백 함수를 등록한다. 등록한 콜백함수를 사용해 로드가 성공하였을 때의 로직, 실패하였을 때의 로직을 구현한다. 버튼을 클릭이 가능하도록 하는 코드를 작성한다.
7.3. Advertisement.Banner.Show(string UnitID, BannerOptions bannerOptions)
배너를 보여준다. BannerOptions class는 배너 클릭과 같은 이벤트가 발생하였을 때 상태 변화에 따른 처리를 담당하는 콜백 함수를 등록할 수 있다.
7.4. Advertisement.Banner.Hide()
배너를 보이지 않게 한다.
7.5. BannerAdExample [2]
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;
public class BannerAdExample : MonoBehaviour
{
// For the purpose of this example, these buttons are for functionality testing:
[SerializeField] Button _loadBannerButton;
[SerializeField] Button _showBannerButton;
[SerializeField] Button _hideBannerButton;
[SerializeField] BannerPosition _bannerPosition = BannerPosition.BOTTOM_CENTER;
[SerializeField] string _androidAdUnitId = "Banner_Android";
[SerializeField] string _iOSAdUnitId = "Banner_iOS";
string _adUnitId = null; // This will remain null for unsupported platforms.
void Start()
{
// Get the Ad Unit ID for the current platform:
#if UNITY_IOS
_adUnitId = _iOSAdUnitId;
#elif UNITY_ANDROID
_adUnitId = _androidAdUnitId;
#endif
// Disable the button until an ad is ready to show:
_showBannerButton.interactable = false;
_hideBannerButton.interactable = false;
// Set the banner position:
Advertisement.Banner.SetPosition(_bannerPosition);
// Configure the Load Banner button to call the LoadBanner() method when clicked:
_loadBannerButton.onClick.AddListener(LoadBanner);
_loadBannerButton.interactable = true;
}
// Implement a method to call when the Load Banner button is clicked:
public void LoadBanner()
{
// Set up options to notify the SDK of load events:
BannerLoadOptions options = new BannerLoadOptions
{
loadCallback = OnBannerLoaded,
errorCallback = OnBannerError
};
// Load the Ad Unit with banner content:
Advertisement.Banner.Load(_adUnitId, options);
}
// Implement code to execute when the loadCallback event triggers:
void OnBannerLoaded()
{
Debug.Log("Banner loaded");
// Configure the Show Banner button to call the ShowBannerAd() method when clicked:
_showBannerButton.onClick.AddListener(ShowBannerAd);
// Configure the Hide Banner button to call the HideBannerAd() method when clicked:
_hideBannerButton.onClick.AddListener(HideBannerAd);
// Enable both buttons:
_showBannerButton.interactable = true;
_hideBannerButton.interactable = true;
}
// Implement code to execute when the load errorCallback event triggers:
void OnBannerError(string message)
{
Debug.Log($"Banner Error: {message}");
// Optionally execute additional code, such as attempting to load another ad.
}
// Implement a method to call when the Show Banner button is clicked:
void ShowBannerAd()
{
// Set up options to notify the SDK of show events:
BannerOptions options = new BannerOptions
{
clickCallback = OnBannerClicked,
hideCallback = OnBannerHidden,
showCallback = OnBannerShown
};
// Show the loaded Banner Ad Unit:
Advertisement.Banner.Show(_adUnitId, options);
}
// Implement a method to call when the Hide Banner button is clicked:
void HideBannerAd()
{
// Hide the banner:
Advertisement.Banner.Hide();
}
void OnBannerClicked() { }
void OnBannerShown() { }
void OnBannerHidden() { }
void OnDestroy()
{
// Clean up the listeners:
_loadBannerButton.onClick.RemoveAllListeners();
_showBannerButton.onClick.RemoveAllListeners();
_hideBannerButton.onClick.RemoveAllListeners();
}
}
8. Advertisement Legacy Error
Advertisement legacy를 설치하는 과정에서 오류가 발생할 수 있다.
아래의 글을 참조한다.
2025.01.27 - [유니티/중급] - Unity Resolving Android Dependencies
Unity Resolving Android Dependencies
1. Resolving Android Dependecies infinite loading Error. Editor version : Unity 2022.3.55f1 본 글의 오류는 유니티 패키지 중 하나인 Advertisement legacy를 설치한 후 발생한 문제이다.Advertisement legacy를 설치하고, 안드
notyu.tistory.com
reference
[1] https://learn.microsoft.com/ko-kr/dotnet/csharp/language-reference/keywords/namespace
네임스페이스 키워드 - C# reference
네임스페이스 키워드를 사용하여 관련 형식 및 기능 구성 - C# 참조
learn.microsoft.com
[2] 코드 출처. https://docs.unity.com/ads/en-us/manual/InitializingTheUnitySDK
Initializing the SDK in Unity
To initialize the SDK, you must reference your project’s Game ID for the appropriate platform. You can locate the Game ID from the Unity Ads Monetization dashboard by selecting the Monetization suite, navigating to your current project, then Settings in
docs.unity.com
[3] ?. null 조건부 연산자
멤버 액세스 및 null 조건부 연산자 및 식: - C# reference
형식 멤버에 액세스하거나 null 조건부 액세스 형식 멤버에 액세스하는 데 사용하는 C# 연산자입니다. 이러한 연산자에는 점 연산자 ('.', 인덱서 - '[', ']', '^' 및 '.)가 포함됩니다. ', 및 호출 - '(', '
learn.microsoft.com
'Unity > Settings' 카테고리의 다른 글
유니티 Resolving Android Dependencies (0) | 2025.01.29 |
---|---|
유니티 Advertisement Legacy - Monetization 연동 (0) | 2025.01.29 |
유니티 안드로이드 API Level Update (API Level 29 ~ 30) (3) | 2021.01.26 |
유니티 안드로이드 폰 연동 (0) | 2020.05.10 |
유니티 구글 플레이 게임 서비스 연동2( 구현하기 ) (0) | 2020.04.25 |