본문 바로가기
GAME Dev/배포_관리

유니티에 구글 애드몹 admob 광고 붙이기

by 루피캣 2023. 9. 19.
반응형

아래 링크에서  Google Mobile Ads Unity Plugin을 다운로드 받는다.

 

https://github.com/googleads/googleads-mobile-unity/releases

 

Releases · googleads/googleads-mobile-unity

Official Unity Plugin for the Google Mobile Ads SDK - googleads/googleads-mobile-unity

github.com

 

패키지 파일을 유니티에서 import

 

구글애드몹  패키지 import
구글애드몹  패키지 import

 

구글에 플러그인 관련 분석 데이터 보낼래 물어보길래 NO 선택

구글애드몹  패키지 import

Assembly 'Assets/ExternalDependencyManager/Editor/1.2.177/Google.IOSResolver.dll' will not be loaded due to errors:
Unable to resolve reference 'UnityEditor.iOS.Extensions.Xcode'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.

에러가 뜬다면 안드로이드에 먼저 광고를 붙일것이기 때문에

Assets - ExternalDependencyManager - Editor - version - Google.IOS Resorlver 선택

구글애드몹  패키지 import

인스펙터 창에 Validate References 체크 해제

구글애드몹  패키지 import

 

유니티 빌드 플랫폼을 안드로이드로 바꾸고

빌드 플랫폼 변경

 

종속항목 자동 관리를 위해 Enable Android Auto-resolution창에서 Enable 선택

Gradle이 실행되고 자동으로 Dependencies를 처리한다.

의존성 자동 관리

 

구글 애드몹 세팅

Google Mobile Ads App ID를 입력해줘야한다.

구글 애드몹 세팅

앱ID는 구글 애드몹 사이트에서 앱을 등록하여 만든다.

url 뒤에 ?hl=ko가 붙으면 한글로 나온다. 

Google AdMob

아직 앱스토어에 올라가지 않았음.

애드몹 사이트에서 광고 세팅

 

애드몹 사이트에서 광고 세팅

AD Unit도 하나 생성

애드몹 사이트에서 광고 세팅

Rewarded 선택하여 유저가 선택에 의해 전면 광고를 보면 보상으로 게임 아이템 주게 

완료하면 앱 ID와 광고 유닛 ID를 확인할 수 있음.

애드몹 사이트에서 광고 세팅

 

위 광고 유닛 ID로 테스트를 하면 안된다. 

테스트 광고 유닛 ID는 별도로 존재한다. 아래 링크 참고

https://developers.google.com/admob/android/test-ads?hl=ko  안드로이드

앱 오프닝 광고 ca-app-pub-3940256099942544/3419835294
적응형 배너 ca-app-pub-3940256099942544/9214589741
배너 ca-app-pub-3940256099942544/6300978111
전면 광고 ca-app-pub-3940256099942544/1033173712
동영상 전면 광고 ca-app-pub-3940256099942544/8691691433
보상형 광고 ca-app-pub-3940256099942544/5224354917
보상형 전면 광고 ca-app-pub-3940256099942544/5354046379
네이티브 광고 고급형 ca-app-pub-3940256099942544/2247696110
네이티브 광고 고급형 동영상 ca-app-pub-3940256099942544/1044960115

https://developers.google.com/admob/ios/test-ads?hl=ko  ios

앱 오프닝 광고 ca-app-pub-3940256099942544/5662855259
적응형 배너 ca-app-pub-3940256099942544/2435281174
배너 ca-app-pub-3940256099942544/2934735716
전면 광고 ca-app-pub-3940256099942544/4411468910
동영상 전면 광고 ca-app-pub-3940256099942544/5135589807
보상형 광고 ca-app-pub-3940256099942544/1712485313
보상형 전면 광고 ca-app-pub-3940256099942544/6978759866
네이티브 광고 고급형 ca-app-pub-3940256099942544/3986624511
네이티브 광고 고급형 동영상 ca-app-pub-3940256099942544/2521693316

 

참고로 광고를 테스트 하는 방법은 두가지 인데 테스트 광고 유닛 ID 사용과 테스트 기기 등록이다.

https://support.google.com/admob/answer/9388275?hl=ko 

 

Scene에 빈 오브젝트를 추가하고 아래 GoogleAdMob 스크립트를 컴포넌트로 등록한다. 

using GoogleMobileAds.Api;
using System;
using UnityEngine;

public class GoogleAdMob : MonoBehaviour
{
#if UNITY_ANDROID
    private string _adUnitId = "ca-app-pub-3940256099942544/5224354917";
#elif UNITY_IPHONE
  private string _adUnitId = "ca-app-pub-3940256099942544/1712485313";
#else
  private string _adUnitId = "unused";
#endif

    // Start is called before the first frame update
    void Start()
    {
        MobileAds.Initialize((InitializationStatus initStatus) =>
        {
            // This callback is called once the MobileAds SDK is initialized.
            LoadRewardedAd();
        });
    }

    private RewardedAd rewardedAd;

    /// <summary>
    /// Loads the rewarded ad.
    /// </summary>
    public void LoadRewardedAd()
    {
        // Clean up the old ad before loading a new one.
        if (rewardedAd != null)
        {
            rewardedAd.Destroy();
            rewardedAd = null;
        }

        Debug.Log("Loading the rewarded ad.");

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

        // send the request to load the ad.
        RewardedAd.Load(_adUnitId, adRequest,
            (RewardedAd ad, LoadAdError error) =>
            {
                // if error is not null, the load request failed.
                if (error != null || ad == null)
                {
                    Debug.LogError("Rewarded ad failed to load an ad " +
                                   "with error : " + error);
                    return;
                }

                Debug.Log("Rewarded ad loaded with response : "
                          + ad.GetResponseInfo());

                rewardedAd = ad;

                RegisterEventHandlers(rewardedAd);

                ShowRewardedAd();
            });
    }

    public void ShowRewardedAd()
    {
        const string rewardMsg =
            "Rewarded ad rewarded the user. Type: {0}, amount: {1}.";

        if (rewardedAd != null && rewardedAd.CanShowAd())
        {
            rewardedAd.Show((Reward reward) =>
            {
                // TODO: Reward the user.
                Debug.Log(string.Format(rewardMsg, reward.Type, reward.Amount));
            });
        }
    }

    private void RegisterEventHandlers(RewardedAd ad)
    {
        // Raised when the ad is estimated to have earned money.
        ad.OnAdPaid += (AdValue adValue) =>
        {
            Debug.Log(String.Format("Rewarded ad paid {0} {1}.",
                adValue.Value,
                adValue.CurrencyCode));
        };
        // Raised when an impression is recorded for an ad.
        ad.OnAdImpressionRecorded += () =>
        {
            Debug.Log("Rewarded ad recorded an impression.");
        };
        // Raised when a click is recorded for an ad.
        ad.OnAdClicked += () =>
        {
            Debug.Log("Rewarded ad was clicked.");
        };
        // Raised when an ad opened full screen content.
        ad.OnAdFullScreenContentOpened += () =>
        {
            Debug.Log("Rewarded ad full screen content opened.");
        };
        // Raised when the ad closed full screen content.
        ad.OnAdFullScreenContentClosed += () =>
        {
            Debug.Log("Rewarded ad full screen content closed.");
            LoadRewardedAd();
        };
        // Raised when the ad failed to open full screen content.
        ad.OnAdFullScreenContentFailed += (AdError error) =>
        {
            Debug.LogError("Rewarded ad failed to open full screen content " +
                           "with error : " + error);
            LoadRewardedAd();
        };
    }
}

게임을 실행하여 해당 씬이 열리면 광고가 바로 나온다.

유니티 구글 애드몹 보상형 광고 테스트

ShowRewardedAd()를 광고 보기 버튼에 연결해주면 됨

 

콘솔을 확인하면 광고를 닫으면 Reward 10을 받았다는 문자열이 출력된다.

유니티 구글 애드몹 보상형 광고 테스트

 

유니티 iOS 빌드 시 
애드몹 라이브러리가 cocoapods의 의존성 관리로 추가될 수 있게 
xcodeproj 파일이 아닌 xcworkspace 파일을 열어
XCode에서 빌드한다. 

유니티 구글 애드몹 Xcode에서 실행

 

참고로 콘텐츠 대상을 13세 미만으로 광고 송출에 제한이 있다.

(애드몹 광고 컨텐츠 등급을 변경해야할지도..)

 

예제 유니티 프로젝트

https://github.com/googleads/googleads-mobile-unity/tree/main/samples/HelloWorld

 

구글 애드몹 유니티 가이드 문서

https://developers.google.com/admob/unity/quick-start?hl=ko 

 

| 앱 출시 후 세팅

 

광고를 테스트 하고 실제 앱을 출시하면 app-ad.txt 파일을 만들어

자신의 웹 서버  root 디렉토리에 올리고

(티스토리에는 root 폴더에 파일을 업로드 할 수 없기 때문에

본인의 웹사이트가 없다면

netlify 같은 무료 웹호스팅을 이용한다.)

 

구글은 스토어 설정 - 스토어 등록정보 연락처 세부정보 - 웹사이트에

애플은 마케팅 URL에 웹사이트 url을 기입해줘야한다.

 

그리고 애드몹 사이트에서 스토어에 출시된 앱을 각 등록해준다.

VIEW ALL APPS 클릭 후

 app-ad.txt 탭 선택하고 설정.

그 후 애드몹은 앱 스토어의 url을 크롤링해서 애드몹 계정이 광고 출력 대상 앱  실제 소유주가 맞나 확인한다.

 

이걸 하지 않으면 광고를 내보내지 않겠다는 광고주들이 있어 필수로 하는게 좋다.

 

크롤링이 완료되면 쿼리 100%를 볼 수 있다.

app-ad.txt

| SKAdNetwork 

애드몹 알림 창에

Some apps haven't been configured to use Apple's SKAdNetwork

라는 경고가 뜬다.

 

iOS14이상에서는 SKAdNetwork를 설정해줘야한다.

 

개인화된 광고를 위해 유저에게 동의를 얻는 것인데,

필수는 아니며 대부분의 유저들은 거부를 하기에 해당 설정은 하지 않아도 될듯?

 

광고 네트워크 ID 설정

https://docs.unity.com/ads/ko-kr/manual/ConfiguringAdNetworkIDs

https://developers.google.com/admob/ios/privacy/strategies?hl=ko

 

반응형
 

Bad Mouse 2

This is amazing Whack a Mole game ★★★★★

badmouse2.netlify.app

댓글