본문 바로가기
Dev/Unity(C#)

Unity Ads / Advertising 광고 넣기(2023.12.05)

by E.Clone 2023. 12. 5.

글 확인 전 참고사항

- Unity Ads 패키지의 이름이 Unity Advertising으로 변경되었습니다. 버전 4.4.1부터는 이 패키지를 Unity 광고 레거시라고 합니다.

- 아래의 내용은 2023년 12월 5일에 공식문서를 참고하여 유니티 2022.3.8.f1(LTS) 버전에서 정상적인 작동을 확인하였습니다.

- [노션페이지]에서 더 나은 스타일로 글을 확인할 수 있습니다.

Unity Ads / Unity Advertising 사용 가이드

  1. https://cloud.unity.com/ 로 접속하여 대시보드 진입
  2. 광고를 넣고자 하는 프로젝트 진입
  3. 서비스 목록 중 Unity Ads Monetization 선택하여, 광고 활성화
    1. I only plans to use Unity Ads(Unity Ads만 사용할 계획입니다) 선택 후 다음
    2. My app is not live in an app store yet(내 앱이 아직 앱 스토어에 게시되지 않았습니다) 선택 후 프로젝트 추가
    3. 본인의 경우 에러 발생 창 나왔지만, Retry 버튼 클릭하면 바로 해결.
    4. 아까 보였던 광고 활성화 버튼이 사라져있으면 OK
  4. Unity Ads Monetization 페이지에서 계속 진행. 설정 가이드 진입.
  5. 가이드에 따라 3개 스텝을 진행.
    1. Install Unity Ads SDK(Unity 광고 SDK 설치)
      1. 개발환경의 Unity로 이동
      2. Window > General > Services 진입하여, Advertisement Legacy 설치
      3. 또한 별개로 Setup Guide 페이지에서 Read integration guide 를 클릭하면 전체 가이드 공식문서가 열리며, 추후 사용할 예시 스크립트도 모두 여기에 적혀있다.
    2. Testing(테스트)
      1. 실제 광고가 아닌 테스트 광고를 사용하기 위해 필요한 절차
      2. Go to Testing 클릭하여 설정 페이지로 이동
      3. Apple App Store 와 Google Play Store 의 편집 버튼을 눌러 Override client test mode 에 체크 한 후, Force test mode ON (i.e. use test ads) for all devices 을 선택하여 모든 장치에서 테스트용 광고를 사용하도록 설정한다.
      4. 추후 실제 광고를 사용하게 된다면 여기서 다시 설정을 바꿔준다.
    3. Configure Ad Units(광고 단위 구성)
      1. 어떤 탬플릿의 광고를 사용할지 확인하기 위한 목적.
      2. Go to Ad Units 버튼 또는 왼쪽의 광고 단위 탭에 접근한다.
      3. 여기서 확인해야 할 것은 상단에 표시된 iOS 게임 ID, 안드로이드 게임 ID 그리고 하단에 나온 광고 단위 ID 이다. 필요에 따라 다른 모양의 광고를 사용하면 되며, 예시로 전면 광고 ID인 Interstitial_Android와 Interstitial_iOS를 사용 해 보겠다.
  6. 광고 적용
    1. 앱 시작 시 ‘SDK 초기화’를 필수적으로 해야하며, 이후 필요한만큼 ‘광고 유닛 표시’ 를 한다.
    2. SDK 초기화를 위해 씬에 빈 오브젝트를 하나 생성하여 아래 스크립트를 적용한다. 게임 시작 시 함께 실행된다. _androidGameId 변수와 _iOSGameId 는 5-c-iii에서 확인한 것을 기재한다.
      • AdsInitializer.cs(포스트 하단)
    3. 전면, 보상형, 배너 타입의 광고 중에 전면 광고를 넣어보자. 각 타입의 구현은 [공식문서]에서 확인할 수 있다. 아래와 같은 스크립트를 방금 생성한 오브젝트에 함께 적용한다. 게임이 시작되고 약 2초 후에 광고의 로드와 표시를 한다. _androidAdUnitId 와 _iOsAdUnitId 에는 각각 안드로이드와 iOS에서 표시될 광고의 타입(유닛)을 넣어주면 되는데, 전면광고를 예로 들면 각각 "Interstitial_Android” 와 “Interstitial_iOS”를 입력 해 주어야 한다. 광고 단위의 ID는 5-c-iii 과정에서 확인한 광고 단위 탭에서 확인 가능하다.
      • InterstitialAdExample.cs(포스트 하단)
    4. 적용하여 실행한 후 2초 뒤 모습은 아래와 같다.
      • 결과 확인

 

7. 보상형 광고 등 이외 내용은 [공식문서]를 참고

 

티스토리 이미지 위치 조정도 안되고, 오더리스트 타입도 설정 안 되고, 들여쓰기 내어쓰기도 안보이고, 코드블럭도 배치 안되고, 글씨 size 설정도 안보이고, 마크다운모드 다녀오면 글 전체 문단 배치가 박살나있고 왜 이러는지 모르겠다. 플랫폼 바꿔야할까 생각중

(소스코드)

// AdsInitializer.cs

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}");
    }
}
// InterstitialAdExample

using UnityEngine;
using UnityEngine.Advertisements;

public class InterstitialAdExample : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] string _androidAdUnitId = "Interstitial_Android";
    [SerializeField] string _iOsAdUnitId = "Interstitial_iOS";
    string _adUnitId;

    void Awake()
    {
        // Get the Ad Unit ID for the current platform:
        _adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
            ? _iOsAdUnitId
            : _androidAdUnitId;
    }
       
    void Start()
    {
        // 2초 후에 광고를 표시합니다
        Invoke("InvokeAd", 2.0f);
    }

    void InvokeAd()
    {
        LoadAd();
        ShowAd();
    }
    // Load content to the Ad Unit:
    public void LoadAd()
    {
        // IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
        Debug.Log("Loading Ad: " + _adUnitId);
        Advertisement.Load(_adUnitId, this);
    }

    // Show the loaded content in the Ad Unit:
    public void ShowAd()
    {
        // Note that if the ad content wasn't previously loaded, this method will fail
        Debug.Log("Showing Ad: " + _adUnitId);
        Advertisement.Show(_adUnitId, this);
    }

    // Implement Load Listener and Show Listener interface methods: 
    public void OnUnityAdsAdLoaded(string adUnitId)
    {
        // Optionally execute code if the Ad Unit successfully loads content.
    }

    public void OnUnityAdsFailedToLoad(string _adUnitId, UnityAdsLoadError error, string message)
    {
        Debug.Log($"Error loading Ad Unit: {_adUnitId} - {error.ToString()} - {message}");
        // Optionally execute code if the Ad Unit fails to load, such as attempting to try again.
    }

    public void OnUnityAdsShowFailure(string _adUnitId, UnityAdsShowError error, string message)
    {
        Debug.Log($"Error showing Ad Unit {_adUnitId}: {error.ToString()} - {message}");
        // Optionally execute code if the Ad Unit fails to show, such as loading another ad.
    }

    public void OnUnityAdsShowStart(string _adUnitId) { }
    public void OnUnityAdsShowClick(string _adUnitId) { }
    public void OnUnityAdsShowComplete(string _adUnitId, UnityAdsShowCompletionState showCompletionState) { }
}
반응형