Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- 백준
- github
- 시작해요 언리얼 2022
- 파이썬
- 프로그래밍
- Tutorial
- Programming
- 재귀
- Algorithm
- DP
- W3Schools
- dfs
- Unity
- guide
- String
- w3school
- 문제풀이
- dynamic
- c++
- C#
- Basic
- loop
- Material
- UE5
- Class
- python
- 기초
- Unreal Engine 5
- 오류
- parameter
Archives
- Today
- Total
행복한 개구리
Unity 광고 수업내용 21.07.22 - Unity Ads, Google AdMob 본문
소셜 로그인/소셜로그인 - Solution
Unity 광고 수업내용 21.07.22 - Unity Ads, Google AdMob
HappyFrog 2021. 7. 22. 12:31실행 전 주의사항
Unity는 모르겠지만 Google AdMob은 실제광고를 테스트하는데 사용하면 밴을 당한다고 합니다.
Unity와 AdMob 둘 다 테스트용 광고링크를 제공하니 주의하여 사용합시다.



- 우선 General - Services를 누르면 나오는 탭에서 Ads를 눌러주자.
- 그러면 오른쪽 사진과 같은 팝업이 나올텐데 오른쪽 상단에 보이는 Off를 눌러서 On으로 바꿔주자.

- On이 되었다면 Install Latest Vesion을 눌러 업데이트 해주자.
- Game Id들은 자동으로 할당되었다.


- 그리고 Unity Dashboard - Monetize를 들어가주자.(대시보드는 저 위에있는 Ads팝업의 Dashboard를 눌러도 되고 직접 접속해도 된다. => 전자추천)
- 그러면 앱을 하나 고르면서 들어갈텐데 광고를 붙일 앱을 선택하고 들어간다.

- 그리고 왼쪽 탭의 Ad Units를 누르면 해당 화면이 나온다.
- 여기서 각 앱스토어의 게임ID를 알 수 있고, 광고 링크들을 복사할 수 있다.
- Banner는 배너광고, Interstitial은 전면광고, Rewarded는 보상이 있는 광고를 말한다.
- 자신이 출시할 플랫폼에 맞게 사용하자.

- 이제 유니티에서 환경을 만들어주자.
- 각 광고별로 버튼들을 만들어줫으며, 배너광고는 숨길 수 있기때문에 Hide버튼을 추가했다.
- Text오브젝트들은 버튼의 이름 또는 광고 종류를 나타내는 것이다.
- UnityAdsMain은 AD매니저개념으로 보면된다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Advertisements;
public class UnityAdsMain : MonoBehaviour, IUnityAdsInitializationListener
{
public string gameId = "자신의 게임ID";
public bool testMode = true;
public void OnInitializationComplete()
{
Debug.Log("Initialize Complete");
}
public void OnInitializationFailed(UnityAdsInitializationError error, string message)
{
Debug.LogFormat("[Unity Ads init failed]\n error: {0}\nmessage: {1}", error, message);
}
private void Awake()
{
Advertisement.Initialize(gameId, testMode, true, this);
}
}
- AdsMain코드.
- Ad를 시작하는 인터페이스가 붙어있으며, Awake로 시작하자마자 Initialize한다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Advertisements;
using UnityEngine.UI;
public class Banner : MonoBehaviour
{
public string adUnitId = "Banner_Android";
public Button btnLoad;
public Button btnShow;
public Button btnHide;
void Start()
{
Advertisement.Banner.SetPosition(BannerPosition.BOTTOM_CENTER);
btnShow.interactable = false;
btnHide.interactable = false;
this.btnLoad.onClick.AddListener(() => {
this.Load();
});
this.btnShow.onClick.AddListener(() => {
this.Show();
});
this.btnHide.onClick.AddListener(() => {
this.Hide();
});
}
private void Load()
{
BannerLoadOptions options = new BannerLoadOptions
{
loadCallback = OnBannerLoaded,
errorCallback = OnBannerError
};
Advertisement.Banner.Load(adUnitId, options);
}
void OnBannerLoaded()
{
Debug.Log("Banner loaded");
btnShow.interactable = true;
btnHide.interactable = true;
}
void OnBannerError(string message)
{
Debug.Log($"Banner Error: {message}");
}
void Show()
{
// Set up options to notify the SDK of show events:
BannerOptions options = new BannerOptions
{
clickCallback = OnBannerClicked,
hideCallback = OnBannerHidden,
showCallback = OnBannerShown
};
Advertisement.Banner.Show(adUnitId, options);
}
void OnBannerClicked() { }
void OnBannerShown() { }
void OnBannerHidden() { }
void Hide()
{
Advertisement.Banner.Hide();
}
}
- Banner코드.
- 콜백을 이용하여 배너의 상태를 설정한다.
- 나머지는 그냥 버튼 상호작용 정도로 보면 된다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;
public class Interstitial : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
public string _adUnitId = "Interstitial_Android";
public Button btnLoad;
public Button btnShow;
private void Start()
{
this.btnShow.interactable = false;
this.btnLoad.onClick.AddListener(() =>
{
LoadAd();
this.btnShow.interactable = true;
});
this.btnShow.onClick.AddListener(() =>
{
this.ShowAd();
});
}
public void LoadAd()
{
Debug.Log("Loading Ad: " + _adUnitId);
Advertisement.Load(_adUnitId, this);
}
public void ShowAd()
{
Debug.Log("Showing Ad: " + _adUnitId);
Advertisement.Show(_adUnitId, this);
}
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 execite 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 execite code if the Ad Unit fails to show, such as loading another ad.
}
public void OnUnityAdsShowStart(string adUnitId)
{
Debug.LogFormat("OnUnityAdsShowStart : {0}", adUnitId);
}
public void OnUnityAdsShowClick(string adUnitId)
{
Debug.LogFormat("OnUnityAdsShowClick : {0}", adUnitId);
}
public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
{
Debug.LogFormat("OnUnityAdsShowComplete \nadUnitId : {0}\nState : {1}", adUnitId, showCompletionState);
}
}
- 전면광고 코드.
- 부착한 인터페이스는 광고가 잘 출력되는지를 확인하기위한 콜백들이며 굳이 사용하지않고 로그만 찍었다.
- 나머지는 Advertisement의 Load, Show를 이용하여 광고만 보여줬다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;
public class Reward : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
public string _adUnitId = "Rewarded_Android";
public Button btnLoad;
public Button btnShow;
void Start()
{
this.btnShow.interactable = false;
this.btnLoad.onClick.AddListener(() =>
{
this.btnShow.interactable = true;
});
this.btnShow.onClick.AddListener(() =>
{
ShowAd();
this.btnShow.interactable = false;
});
}
public void LoadAd()
{
Debug.Log("Loading Ad: " + _adUnitId);
Advertisement.Load(_adUnitId, this);
}
public void ShowAd()
{
Advertisement.Show(_adUnitId, this);
}
public void OnUnityAdsAdLoaded(string placementId)
{
Debug.LogFormat("OnUnityAdsAdLoaded : {0}", placementId);
}
public void OnUnityAdsFailedToLoad(string placementId, UnityAdsLoadError error, string message)
{
Debug.LogFormat("OnUnityAdsFailedToLoad : {0}, {1}, {2}", placementId, error, message);
}
public void OnUnityAdsShowFailure(string placementId, UnityAdsShowError error, string message)
{
Debug.LogFormat("OnUnityAdsShowFailure : {0}, {1}, {2}", placementId, error, message);
}
public void OnUnityAdsShowStart(string placementId)
{
Debug.LogFormat("OnUnityAdsShowStart : {0}", placementId);
}
public void OnUnityAdsShowClick(string placementId)
{
Debug.LogFormat("OnUnityAdsShowClick : {0}", placementId);
}
public void OnUnityAdsShowComplete(string placementId, UnityAdsShowCompletionState showCompletionState)
{
Debug.LogFormat("OnUnityAdsShowComplete: {0}, {1}", placementId, showCompletionState.ToString());
if (_adUnitId.Equals(placementId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
{
Debug.Log("Unity Ads Rewarded Ad Completed");
// Grant a reward.
Debug.Log("보상을 받았습니다.");
// Load another ad:
Advertisement.Load(_adUnitId, this);
}
}
}
- 보상광고 코드.
- 전면광고와 비슷한 코드지만 인터페이스의 마지막 부분이 조금 다르다.
- OnUnityAdsShowComplete가 있는데, 이는 광고 시청을 완료했을 때 보상을 주기위해 있는 것이다.


- 녹스에서 돌려보니 배너는 왼쪽과 같이 나오고
- 전면광고와 보상광고는 오른쪽과 같이 나왔다. => 둘이 같은 영상광고여서 한장만 찍었다.

- 보상광고를 ADB로 로그를 찍어보니 성공했다고 나왔다.
Google AdMob
Google AdMob: 모바일 앱 수익 창출
인앱 광고를 사용하여 모바일 앱에서 더 많은 수익을 창출하고, 사용이 간편한 도구를 통해 유용한 분석 정보를 얻고 앱을 성장시켜 보세요.
admob.google.com




- 애드몹에 회원가입을 해주자.
- 그리고 앱 등록까지 하는데, 앱스토어에 등록을 안해도 상관없다. => 나중에 할 수 있기 때문.

- 완료된 화면

- 성공적으로 앱까지 연결했다면 광고 단위 탭으로 들어갈 수 있을 것이다.
- 시작해주자.

- 이렇게 여러 광고종류들이 나온다.
- 나는 리워드(보상형 광고)로 진행했다.

- 해당 설정을 해주고 생성하자.
- 나는 이름만 "리워드"로 해주고 넘어갔다.


- 생성했다면 왼쪽 사진과 같은 화면이 나온 다음 완료를 누르면
- 오른쪽 사진과 같이 목록에 생성되었음을 확인할 수 있다.

- 그리고 광고단위 설정에서 생성된 ID를 UnityEditor에 있는 Ads Settings에 기입해준다.

- 씬 구조는 위와같이 만들었으며 스크립트는 GoogleAdMobMain에만 할당되었다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using GoogleMobileAds.Api;
using System;
public class GoogleAdMobMain : MonoBehaviour
{
public string adUnitId = "ca-app-pub-3940256099942544/5224354917";
private RewardedAd rewardedAd;
public Button btnShow;
private void Awake()
{
this.btnShow.onClick.AddListener(() => {
this.btnShow.interactable = false;
StartCoroutine(this.WaitForLoadAds(()=> {
this.UserChoseToWatchAd();
this.btnShow.interactable = true;
}));
});
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(initStatus => {
Debug.LogFormat("initStatus: {0}", initStatus);
});
}
void Start()
{
this.rewardedAd = new RewardedAd(adUnitId);
// Called when an ad request has successfully loaded.
this.rewardedAd.OnAdLoaded += HandleRewardedAdLoaded;
// Called when an ad request failed to load.
this.rewardedAd.OnAdFailedToLoad += RewardedAd_OnAdFailedToLoad;
// Called when an ad is shown.
this.rewardedAd.OnAdOpening += HandleRewardedAdOpening;
// Called when an ad request failed to show.
this.rewardedAd.OnAdFailedToShow += HandleRewardedAdFailedToShow;
// Called when the user should be rewarded for interacting with the ad.
this.rewardedAd.OnUserEarnedReward += HandleUserEarnedReward;
// Called when the ad is closed.
this.rewardedAd.OnAdClosed += HandleRewardedAdClosed;
// Create an empty ad request.
this.request = new AdRequest.Builder().Build();
}
private AdRequest request;
private IEnumerator WaitForLoadAds(System.Action callback) {
// Load the rewarded ad with the request.
this.rewardedAd.LoadAd(request);
while (true) {
if (this.rewardedAd.IsLoaded()) {
break;
}
yield return null;
}
callback();
}
private void UserChoseToWatchAd()
{
if (this.rewardedAd.IsLoaded())
{
this.rewardedAd.Show();
}
}
private void RewardedAd_OnAdFailedToLoad(object sender, AdFailedToLoadEventArgs e)
{
Debug.Log("RewardedAd_OnAdFailedToLoad");
}
public void HandleRewardedAdLoaded(object sender, EventArgs args)
{
Debug.Log("HandleRewardedAdLoaded event received");
}
public void HandleRewardedAdOpening(object sender, EventArgs args)
{
Debug.Log("HandleRewardedAdOpening event received");
}
public void HandleRewardedAdFailedToShow(object sender, AdErrorEventArgs args)
{
Debug.Log("HandleRewardedAdFailedToShow event received with message: " + args.Message);
}
public void HandleRewardedAdClosed(object sender, EventArgs args)
{
Debug.Log("HandleRewardedAdClosed event received");
}
public void HandleUserEarnedReward(object sender, Reward args)
{
string type = args.Type;
double amount = args.Amount;
Debug.Log("HandleRewardedAdRewarded event received for " + amount.ToString() + " " + type);
}
}
- 그리고 위 코드와 같이 작성했다.
- 콜백 메서드들은 로그만 띄우도록 했다.
- 핵심기능은 Awake에 있다.
- 그리고 AdUnityId는 API에서 알려준 Test용 Ad를 사용하였다.
- UnityAds와는 다르게 IAP를 사용하지않고 UI의 Button클래스를 사용한다.

- AdMob페이지에서 광고설정을 하고 앱으로 코드를 작성한 뒤 실행시키면 위와같이 DeviceID를 받아올 수 있다.
- => ADB를 "adb logcat -s Ads"로 검색하면 편하게 찾을 수 있다.

- 그리고 상단에 TestAd가 출력되며 광고가 나오는 것을 확인할 수 있다.
'소셜 로그인 > 소셜로그인 - Solution' 카테고리의 다른 글
소셜로그인 중 JSON 데이터 파싱 오류 (0) | 2021.07.09 |
---|---|
Git 메타버전 불일치 에러 (0) | 2021.07.08 |
GPGS 인증실패 오류 (0) | 2021.07.07 |
Unity3D 팀프 21.07.07. GPGS로그인 연동 SignInRequired 이슈 (0) | 2021.07.07 |
GPGS KeyStore 관련 오류 (0) | 2021.06.18 |