TIL(2024,07,26)최종 프로젝트 1차구현 하나씩 만들기

김보근·2024년 7월 26일

Unity

목록 보기
52/113
post-thumbnail

TIL(Today I Learned)

개요

오늘은 유니티 프로젝트에서 Google Mobile Ads SDK를 사용하여 보상형 광고를 구현하는 방법을 배웠습니다. 보상형 광고는 사용자가 비디오 광고를 시청하면 앱 내 보상을 제공하는 광고 형식입니다. 이번 구현은 Google Mobile Ads SDK 설정, 보상형 광고를 관리하는 싱글톤 클래스 생성, 광고 로드, 다양한 광고 이벤트 처리로 구성됩니다.

단계별 구현
1. Google Mobile Ads SDK 설정
먼저, Google Mobile Ads SDK를 유니티 프로젝트에 통합해야 합니다. Unity Package Manager를 통해 Git URL에서 SDK를 추가하거나, Unity에서 제공하는 다른 방법을 사용할 수 있습니다.

  1. 광고 단위 ID 생성
    Google AdMob 계정에 로그인하여 실제 광고 단위 ID를 생성합니다. 테스트를 위해 제공된 테스트 광고 단위 ID를 사용할 수도 있습니다.

  2. 보상형 광고 스크립트 작성
    보상형 광고를 로드하고 표시하기 위한 스크립트를 작성합니다. 아래는 보상형 광고를 관리하는 RewardedAdExample 클래스의 코드입니다.

using System;
using GoogleMobileAds.Api;
using UnityEngine;

public class RewardedAdExample : MonoBehaviour
{
    private RewardedAd rewardedAd;
    private string adUnitId;

    // Singleton instance
    public static RewardedAdExample Instance { get; private set; }

    void Awake()
    {
        // Implement Singleton pattern
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject); // Prevent the game object from being destroyed between scenes
        }
        else
        {
            Destroy(gameObject);
        }
    }

    void Start()
    {
        // Initialize Mobile Ads SDK
        MobileAds.Initialize(initStatus => { });

#if UNITY_ANDROID
        adUnitId = "ca-app-pub-3940256099942544/5224354917"; // Test ID
#elif UNITY_IPHONE
        adUnitId = "ca-app-pub-3940256099942544/1712485313"; // Test ID
#else
        adUnitId = "unexpected_platform";
#endif

        LoadRewardedAd();
    }

    private void LoadRewardedAd()
    {
        if (rewardedAd != null)
        {
            rewardedAd.Destroy();
            rewardedAd = null;
        }

        // Create a new AdRequest
        AdRequest adRequest = new AdRequest.Builder().Build();

        // Load a new rewarded ad
        RewardedAd.Load(adUnitId, adRequest, (RewardedAd ad, LoadAdError error) =>
        {
            if (error != null)
            {
                Debug.LogError("Rewarded ad failed to load: " + error);
                return;
            }

            if (ad == null)
            {
                Debug.LogError("Rewarded ad failed to load.");
                return;
            }

            rewardedAd = ad;
            RegisterEventHandlers(rewardedAd);
        });
    }

    public void ShowRewardedAd(Action<Reward> onUserEarnedReward)
    {
        if (rewardedAd != null && rewardedAd.CanShowAd())
        {
            rewardedAd.Show((Reward reward) =>
            {
                Debug.Log("User earned reward: " + reward.Type + ", amount: " + reward.Amount);
                onUserEarnedReward?.Invoke(reward);
            });
        }
        else
        {
            Debug.Log("Rewarded ad is not ready yet.");
        }
    }

    private void RegisterEventHandlers(RewardedAd ad)
    {
        ad.OnAdPaid += (AdValue adValue) =>
        {
            Debug.Log("Rewarded ad received a paid event.");
        };

        ad.OnAdClicked += () =>
        {
            Debug.Log("Rewarded ad was clicked.");
        };

        ad.OnAdImpressionRecorded += () =>
        {
            Debug.Log("Rewarded ad impression recorded.");
        };

        ad.OnAdFullScreenContentOpened += () =>
        {
            Debug.Log("Rewarded ad full screen content opened.");
        };

        ad.OnAdFullScreenContentClosed += () =>
        {
            Debug.Log("Rewarded ad full screen content closed.");
            LoadRewardedAd(); // Reload ad after it's closed
        };

        ad.OnAdFullScreenContentFailed += (AdError error) =>
        {
            Debug.LogError("Rewarded ad full screen content failed to open: " + error);
        };
    }
}

필드 및 싱글톤 인스턴스 선언

private RewardedAd rewardedAd;
private string adUnitId;

public static RewardedAdExample Instance { get; private set; }

RewardedAd rewardedAd: 보상형 광고 객체를 저장할 변수입니다.
string adUnitId: 광고 단위 ID를 저장할 변수입니다.
public static RewardedAdExample Instance { get; private set; }: 싱글톤 패턴을 구현하여 이 클래스의 인스턴스가 하나만 존재하도록 합니다.

Start 메서드

void Start()
{
    MobileAds.Initialize(initStatus => { });

    #if UNITY_ANDROID
        adUnitId = "ca-app-pub-3940256099942544/5224354917";
    #elif UNITY_IPHONE
        adUnitId = "ca-app-pub-3940256099942544/1712485313";
    #else
        adUnitId = "unexpected_platform";
    #endif

    LoadRewardedAd();
}

MobileAds.Initialize(initStatus => { });: Google Mobile Ads SDK를 초기화합니다.
플랫폼에 따라 광고 단위 ID를 설정합니다.
LoadRewardedAd(): 보상형 광고를 로드합니다.

LoadRewardedAd 메서드

private void LoadRewardedAd()
{
    if (rewardedAd != null)
    {
        rewardedAd.Destroy();
        rewardedAd = null;
    }

    AdRequest adRequest = new AdRequest.Builder().Build();

    RewardedAd.Load(adUnitId, adRequest, (RewardedAd ad, LoadAdError error) =>
    {
        if (error != null)
        {
            Debug.LogError("Rewarded ad failed to load: " + error);
            return;
        }

        if (ad == null)
        {
            Debug.LogError("Rewarded ad failed to load.");
            return;
        }

        rewardedAd = ad;
        RegisterEventHandlers(rewardedAd);
    });
}
  • 이전에 로드된 광고 객체가 있으면 파괴합니다.
  • 광고 요청 객체를 생성합니다.
  • 광고를 로드하고 콜백을 통해 결과를 처리합니다.
  • 광고 로드 실패 시 오류를 로그에 출력합니다.
  • 광고 로드 성공 시 이벤트 핸들러를 등록합니다.

ShowRewardedAd 메서드

public void ShowRewardedAd(Action<Reward> onUserEarnedReward)
{
    if (rewardedAd != null && rewardedAd.CanShowAd())
    {
        rewardedAd.Show((Reward reward) =>
        {
            Debug.Log("User earned reward: " + reward.Type + ", amount: " + reward.Amount);
            onUserEarnedReward?.Invoke(reward);
        });
    }
    else
    {
        Debug.Log("Rewarded ad is not ready yet.");
    }
}
  • 광고가 로드되고 표시할 준비가 되었는지 확인합니다.
  • 광고를 표시하고 사용자가 보상을 받았을 때 콜백을 호출합니다.

RegisterEventHandlers 메서드

private void RegisterEventHandlers(RewardedAd ad)
{
    ad.OnAdPaid += (AdValue adValue) =>
    {
        Debug.Log("Rewarded ad received a paid event.");
    };

    ad.OnAdClicked += () =>
    {
        Debug.Log("Rewarded ad was clicked.");
    };

    ad.OnAdImpressionRecorded += () =>
    {
        Debug.Log("Rewarded ad impression recorded.");
    };

    ad.OnAdFullScreenContentOpened += () =>
    {
        Debug.Log("Rewarded ad full screen content opened.");
    };

    ad.OnAdFullScreenContentClosed += () =>
    {
        Debug.Log("Rewarded ad full screen content closed.");
        LoadRewardedAd(); // 광고가 닫힌 후 새 광고를 로드합니다.
    };

    ad.OnAdFullScreenContentFailed += (AdError error) =>
    {
        Debug.LogError("Rewarded ad full screen content failed to open: " + error);
    };
}
  • 다양한 광고 이벤트에 대한 로그를 출력하는 이벤트 핸들러를 등록합니다.
  • 광고가 닫히면 새로운 광고를 로드합니다

트러블슈팅

광고가 로드되지 않음

광고 단위 ID가 올바른지 확인합니다.
네트워크 연결 상태를 확인합니다.
AdMob 계정 설정이 올바른지 확인합니다.

광고가 표시되지 않음
rewardedAd.CanShowAd()가 true를 반환하는지 확인합니다.
LoadRewardedAd() 메서드가 성공적으로 호출되었는지 확인합니다.

이벤트 핸들러가 호출되지 않음
RegisterEventHandlers() 메서드가 광고 객체에 제대로 이벤트를 등록했는지 확인합니다.

결론

오늘은 유니티에서 Google Mobile Ads SDK를 사용하여 보상형 광고를 구현하는 방법을 배웠습니다. 광고 단위 ID를 실제 ID로 변경하고, 광고 설정을 확인한 후 앱을 배포하면 보상형 광고를 통해 사용자에게 추가적인 인센티브를 제공할 수 있습니다.

profile
게임개발자꿈나무

0개의 댓글