Skip to content

Instantly share code, notes, and snippets.

@nooralibutt
Last active March 21, 2021 20:19
Show Gist options
  • Save nooralibutt/cf8b734a635e01a809b3 to your computer and use it in GitHub Desktop.
Save nooralibutt/cf8b734a635e01a809b3 to your computer and use it in GitHub Desktop.
Unity Ad Controller for multiple Ad Networks
This script is written To Handle Major Ad networks, Cache Management and their callback methods for Unity
Ad Networks Includes:
1- Chartboost Interstitial & Rewarded Video
2- AppLovin Interstitial & Rewarded Video
3- Admob Interstitial & Banner
4- UnityAds Video Interstitial & Rewarded Video
Usage:
Attach this script to an empty GameObject.
Change Ad IDs in script:
// Admob
private const string Admob_iOS_Banner_ID = "ca-app-pub-8949389946267549/9473652319";
private const string Admob_iOS_Interestitial_ID = "ca-app-pub-8949389946267549/8753798716";
private const string Admob_Android_Banner_ID = "ca-app-pub-8949389946267549/4305945912";
private const string Admob_Android_Interestitial_ID = "ca-app-pub-8949389946267549/4404324314";
// AppLovin
private string AppLovin_SDK_KEY = "-8UPgneTQnQwkR_y4zSOx3RZE1HnncAlle9QPpurZIlIlkEphgCcldBzfTlR4vBqTKEz77ohPX-9GDyyv9Zdom";
// Unity Ads
private const string Unity_Ads_iOS_GAME_ID = "72907";
private const string Unity_Ads_Android_GAME_ID = "73557";
Change Banner Ad Position:
private const AdPosition bannerPosition = AdPosition.Top;
// It will automatically decide which ad is available and display that Ad
AdController.SharedInstance ().ShowBestFullscreenAd ();
// It will show Ad Mob Banner
AdController.SharedInstance ().ShowAdmobBanner ();
// It will Hide Ad Mob Banner
AdController.SharedInstance ().HideAdmobBanner ();
// It will Show Chartboost More Apps Dialogue
AdController.SharedInstance ().ShowChartboostMoreApps ();
// This Controller handles cache of ads by itself but To forcefully cache everything
AdController.SharedInstance ().CacheEverything();
// Unity Ad Controller for multiple Ad Networks
// Copyrights SKill Knight Studios 2015
// Author: Noor Ali Butt
// v1.0
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using ChartboostSDK;
using GoogleMobileAds.Api;
using UnityEngine.Advertisements;
using System;
public enum AdStatus {Shown, Skipped, Completed, Failed}
public class AdController : MonoBehaviour {
public delegate void AdAction(AdStatus status, string mesg);
public static event AdAction onRewardedVideoAd;
public bool InternalLoggingEnabled = true;
public bool ExternalLoggingEnabled = true;
private bool canShowBanner = false;
public Text logText;
private static AdController sharedInstance;
private InterstitialAd admobInterstitialAd;
private BannerView admobBannerView;
// Admob
private const string Admob_iOS_Banner_ID = "38_Characters_iOS_Banner_ID_Here";
private const string Admob_iOS_Interestitial_ID = "38_Characters_iOS_Interstitial_ID_Here";
private const string Admob_Android_Banner_ID = "38_Characters_Android_Banner_ID_Here";
private const string Admob_Android_Interestitial_ID = "38_Characters_Android_Interstitial_ID_Here";
// AppLovin
private string AppLovin_SDK_KEY = "86_Characters_ID_Here";
// Unity Ads
private const string Unity_Ads_iOS_GAME_ID = "5_Digits_iOS_ID_Here";
private const string Unity_Ads_Android_GAME_ID = "5_Digits_Android_ID_Here";
private const string Unity_Ads_VIDEO_PLACEMENT_ID = "defaultZone";
private const string Unity_Ads_REWARDED_VIDEO_PLACEMENT_ID = "rewardedVideoZone";
private const AdPosition bannerPosition = AdPosition.Top;
#region Unity_Life_Cycle_Calls
void Awake() {
sharedInstance = this;
DontDestroyOnLoad (gameObject);
InitUnityAds ();
}
// Use this for initialization
void Start () {
AppLovin.SetSdkKey (AppLovin_SDK_KEY);
AppLovin.InitializeSdk ();
AppLovin.SetUnityAdListener (gameObject.name);
Invoke ("CacheEverything", 2);
}
void OnEnable() {
// Chartboost Delegate Methods
Chartboost.didFailToLoadInterstitial += didFailToLoadInterstitial;
Chartboost.didCacheInterstitial += didCacheInterstitial;
Chartboost.didDisplayInterstitial += didDisplayInterstitial;
Chartboost.didFailToLoadMoreApps += didFailToLoadMoreApps;
Chartboost.didCacheMoreApps += didCacheMoreApps;
Chartboost.didFailToLoadRewardedVideo += didFailToLoadRewardedVideo;
Chartboost.didCacheRewardedVideo += didCacheRewardedVideo;
Chartboost.didCompleteRewardedVideo += didCompleteRewardedVideo;
}
void OnDisable() {
// Chartboost Delegate Methods
Chartboost.didFailToLoadInterstitial -= didFailToLoadInterstitial;
Chartboost.didCacheInterstitial -= didCacheInterstitial;
Chartboost.didDisplayInterstitial -= didDisplayInterstitial;
Chartboost.didFailToLoadMoreApps -= didFailToLoadMoreApps;
Chartboost.didCacheMoreApps -= didCacheMoreApps;
Chartboost.didFailToLoadRewardedVideo -= didFailToLoadRewardedVideo;
Chartboost.didCacheRewardedVideo -= didCacheRewardedVideo;
Chartboost.didCompleteRewardedVideo -= didCompleteRewardedVideo;
}
void OnDestroy() {
// Destroying Admob Interstitial
if (admobInterstitialAd != null) {
admobInterstitialAd.Destroy();
}
// Destroying Admob Bannerview
if (admobBannerView != null) {
admobBannerView.Destroy();
}
}
#endregion
public void CacheEverything() {
// Caching More Apps
if (!Chartboost.hasMoreApps(CBLocation.Default)) {
Chartboost.cacheMoreApps(CBLocation.Default);
}
// Caching Chartboost
if (!Chartboost.hasInterstitial(CBLocation.Default)) {
Chartboost.cacheInterstitial(CBLocation.Default);
}
// Caching AppLovin
if (!AppLovin.HasPreloadedInterstitial()) {
AppLovin.PreloadInterstitial();
}
// Requesting Admob Interstitial
if (admobInterstitialAd == null || !admobInterstitialAd.IsLoaded()) {
RequestAdmobInterstitial();
}
Chartboost.setShouldDisplayLoadingViewForMoreApps (true);
}
public void CacheRewardedVideos() {
if (!isEditor()) {
// Caching CB Rewarded Video
if (!Chartboost.hasRewardedVideo (CBLocation.Default)) {
Chartboost.cacheRewardedVideo (CBLocation.Default);
}
// Caching AppLovin Rewarded Video
if (!AppLovin.IsIncentInterstitialReady ()) {
AppLovin.LoadRewardedInterstitial ();
}
}
}
public static bool isEditor() {
return Application.platform == RuntimePlatform.OSXEditor;
}
public static AdController SharedInstance()
{
return sharedInstance;
}
#region Chartboost Delegate Methods
void didDisplayInterstitial(CBLocation location){
AddLog("CB didDisplayInterstitial: " + location);
}
void didFailToLoadInterstitial(CBLocation location, CBImpressionError error) {
AddLog(string.Format("CB didFailToLoadInterstitial: {0} at location {1}", error, location));
}
void didCacheInterstitial(CBLocation location) {
AddLog("CB didCacheInterstitial: " + location);
}
void didFailToLoadMoreApps(CBLocation location, CBImpressionError error) {
AddLog(string.Format("CB didFailToLoadMoreApps: {0} at location: {1}", error, location));
}
void didCacheMoreApps(CBLocation location) {
AddLog(string.Format("CB didCacheMoreApps at location: {0}", location));
}
void didFailToLoadRewardedVideo(CBLocation location, CBImpressionError error) {
AddLog(string.Format("CB didFailToLoadRewardedVideo: {0} at location {1}", error, location));
}
void didCacheRewardedVideo(CBLocation location) {
AddLog("CB didCacheRewardedVideo: " + location);
}
void didCompleteRewardedVideo(CBLocation location, int reward) {
AddLog(string.Format("CB didCompleteRewardedVideo: reward {0} at location {1}", reward, location));
if (onRewardedVideoAd != null) {
onRewardedVideoAd(AdStatus.Completed , "CB Rewarded Video Ad was successfully Completed.");
}
}
#endregion
#region AppLovin Delegate Methods
void onAppLovinEventReceived(string ev){
if(ev.Contains("DISPLAYEDINTER")) {
// An ad was shown. Pause the game.
AddLog("AppLovin Shown");
}
else if(ev.Contains("HIDDENINTER")) {
// Ad ad was closed. Resume the game.
// If you're using PreloadInterstitial/HasPreloadedInterstitial, make a preload call here.
AppLovin.PreloadInterstitial();
}
else if(ev.Contains("LOADEDINTER")) {
// An interstitial ad was successfully loaded.
AddLog("AppLovin interstitial ad was successfully loaded");
}
else if(string.Equals(ev, "LOADINTERFAILED")) {
// An interstitial ad failed to load.
AddLog("AppLovin interstitial ad failed to load.");
}
if(ev.Contains("REWARDAPPROVEDINFO")){
// The format would be "REWARDAPPROVEDINFO|AMOUNT|CURRENCY" so "REWARDAPPROVEDINFO|10|Coins" for example
// string delimeter = "|";
//
// // Split the string based on the delimeter
// string[] split = ev.Split(delimeter);
//
// // Pull out the currency amount
// double amount = double.Parse(split[1]);
//
// // Pull out the currency name
// string currencyName = split[2];
//
// // Do something with the values from above. For example, grant the coins to the user.
//// updateBalance(amount, currencyName);
// AddLog(string.Format("didCompleteRewardedVideo: reward {0} at location {1}", amount, currencyName));
AddLog("didCompleteRewardedVideo");
if (onRewardedVideoAd != null) {
onRewardedVideoAd(AdStatus.Completed , "AppLovin Rewarded Video Ad was successfully Completed.");
}
}
else if(ev.Contains("LOADEDREWARDED")) {
// A rewarded video was successfully loaded.
AddLog("AppLovin didCacheRewardedVideo: ");
}
else if(ev.Contains("LOADREWARDEDFAILED")) {
// A rewarded video failed to load.
AddLog("AppLovin didFailToLoadRewardedVideo");
}
else if(ev.Contains("HIDDENREWARDED")) {
// A rewarded video was closed. Preload the next rewarded video.
AppLovin.LoadRewardedInterstitial();
}
}
#endregion
#region UI_Methods
private void AddLog(string text) {
if (logText != null) {
logText.text += text + "\n";
}
if (ExternalLoggingEnabled) {
// AndroidDialogAndToastBinding.instance.toastLong (text);
}
if (InternalLoggingEnabled) {
Debug.Log(text);
}
}
/// <summary>
/// Shows the best fullscreen ad by Priority
/// 1- Show Chartboost else Cache it and
/// 2- Show Applovin else Cache it and
/// 3- Show Unity Video Ad else Cache it
/// 4- Show Admob else Cache it
/// </summary>
public void ShowBestFullscreenAd() {
if (!ShowChartboostFullscreenAd ()) {
if (!ShowAppLovinFullScreenAd()) {
if (!ShowUnityAd()) {
if (!ShowAdmobFullscreenAd()) {
}
}
}
}
}
/// <summary>
/// Shows the best Rewarded Video ad by Priority
/// 1- Show Chartboost else Cache it and
/// 2- Show Unity Ad else Cache it and
/// 3- Show AppLovin else Cache it
/// </summary>
public bool ShowBestRewardedVideo() {
if (!ShowChartboostRewardedVideoAd ()) {
if (!ShowUnityRewardedVideoAd()) {
if (!ShowAppLovinRewardedVideoAd()) {
return false;
}
}
}
return true;
}
/// <summary>
/// If It has Chartboost Full Screen Ad then it shows else
/// It would send cache Full Screen Ad
/// </summary>
/// <returns><c>true</c>, if Chartboost full screen ad was shown, <c>false</c> otherwise.</returns>
public bool ShowChartboostFullscreenAd() {
if (Chartboost.hasInterstitial (CBLocation.Default)) {
Chartboost.showInterstitial (CBLocation.Default);
return true;
} else {
Chartboost.cacheInterstitial(CBLocation.Default);
return false;
}
}
/// <summary>
/// If Admob has Loaded Full Screen Ad then it shows else
/// It would send new Ad Request to load ad
/// </summary>
/// <returns><c>true</c>, if Admob full screen ad was shown, <c>false</c> otherwise.</returns>
public bool ShowAdmobFullscreenAd() {
if (admobInterstitialAd == null) {
RequestAdmobInterstitial();
return false;
}
else if (admobInterstitialAd.IsLoaded()) {
admobInterstitialAd.Show();
return true;
} else {
admobInterstitialAd.LoadAd(new AdRequest.Builder().Build());
return false;
}
}
/// <summary>
/// If It has more apps then it shows more apps else
/// It would send cache More Apps
/// </summary>
/// <returns><c>true</c>, if chartboost more apps was shown, <c>false</c> otherwise.</returns>
public bool ShowChartboostMoreApps() {
if (Chartboost.hasMoreApps (CBLocation.Default)) {
Chartboost.showMoreApps (CBLocation.Default);
return true;
} else {
Chartboost.cacheMoreApps(CBLocation.Default);
return false;
}
}
/// <summary>
/// If It has AppLovin Full Screen Ad then it shows else
/// It would send cache Full Screen Ad
/// </summary>
/// <returns><c>true</c>, if app lovin full screen ad was shown, <c>false</c> otherwise.</returns>
public bool ShowAppLovinFullScreenAd() {
if (AppLovin.HasPreloadedInterstitial ()) {
AppLovin.ShowInterstitial ();
return true;
} else {
AppLovin.PreloadInterstitial();
return false;
}
}
public bool ShowUnityAd() {
if (!Advertisement.isInitialized) {
InitUnityAds();
return false;
} else if (Advertisement.IsReady(Unity_Ads_VIDEO_PLACEMENT_ID)) {
ShowOptions options = new ShowOptions();
options.resultCallback = HandleShowResult;
Advertisement.Show(Unity_Ads_VIDEO_PLACEMENT_ID, options);
}
return true;
}
public void ShowAdmobBanner() {
canShowBanner = true;
if (admobBannerView == null) {
RequestBanner (bannerPosition);
} else {
admobBannerView.Show();
}
}
public void HideAdmobBanner() {
canShowBanner = false;
if (admobBannerView != null) {
admobBannerView.Hide();
}
}
public bool ShowUnityRewardedVideoAd() {
if (!Advertisement.isInitialized) {
InitUnityAds();
return false;
} else if (Advertisement.IsReady(Unity_Ads_REWARDED_VIDEO_PLACEMENT_ID)) {
ShowOptions options = new ShowOptions { resultCallback = HandleRewardedVideoShowResult };
Advertisement.Show(Unity_Ads_REWARDED_VIDEO_PLACEMENT_ID, options);
return true;
}
return false;
}
public bool ShowAppLovinRewardedVideoAd () {
if (AppLovin.IsIncentInterstitialReady ()) {
AppLovin.ShowRewardedInterstitial ();
return true;
} else {
AppLovin.LoadRewardedInterstitial();
return false;
}
}
public bool ShowChartboostRewardedVideoAd() {
if (Chartboost.hasRewardedVideo (CBLocation.Default)) {
Chartboost.showRewardedVideo (CBLocation.Default);
return true;
} else {
Chartboost.cacheRewardedVideo(CBLocation.Default);
return false;
}
}
public void ShowGameLaunchAd () {
if (!ShowChartboostFullscreenAd ()) {
if (!ShowAppLovinFullScreenAd()) {
if (!ShowUnityAd()) {
if (!ShowAdmobFullscreenAd()) {
}
}
}
}
}
public void ShowGameOverAd () {
if (!ShowUnityAd ()) {
if (!ShowChartboostFullscreenAd()) {
if (!ShowAppLovinFullScreenAd()) {
if (!ShowAdmobFullscreenAd()) {
}
}
}
}
}
public void ShowMoreAppsCloseAd () {
if (!ShowAdmobFullscreenAd ()) {
if (!ShowChartboostFullscreenAd()) {
if (!ShowAppLovinFullScreenAd()) {
if (!ShowUnityAd()) {
}
}
}
}
}
public void ShowReturnToMainMenuAd () {
if (!ShowAppLovinFullScreenAd ()) {
if (!ShowChartboostFullscreenAd()) {
if (!ShowUnityAd()) {
if (!ShowAdmobFullscreenAd()) {
}
}
}
}
}
#endregion
#region AdMob_Banner_Methods_And_Delegates
private void RequestBanner(AdPosition position)
{
string adUnitId = "unexpected_platform";
if (Application.platform == RuntimePlatform.Android) {
adUnitId = Admob_Android_Banner_ID;
} else if(Application.platform == RuntimePlatform.IPhonePlayer){
adUnitId = Admob_iOS_Banner_ID;
}
// Create a smart banner at the top of the screen.
admobBannerView = new BannerView(adUnitId, AdSize.SmartBanner, position);
// Called when an ad request has successfully loaded.
admobBannerView.AdLoaded += HandleBannerAdLoaded;
// Called when an ad request failed to load.
admobBannerView.AdFailedToLoad += HandleBannerAdFailedToLoad;
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the banner with the request.
admobBannerView.LoadAd(request);
}
public void HandleBannerAdLoaded(object sender, EventArgs args)
{
if (admobBannerView != null) {
if (canShowBanner) {
admobBannerView.Show ();
} else {
admobBannerView.Hide();
}
}
AddLog("Admob Banner HandleAdLoaded event received.");
// Handle the ad loaded event.
}
public void HandleBannerAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
AddLog("Admob Banner Failed to load: " + args.Message);
// Handle the ad failed to load event.
}
#endregion
#region AdMob_Interstitial_Methods_And_Delegates
private void RequestAdmobInterstitial()
{
string adUnitId = "unexpected_platform";
if (Application.platform == RuntimePlatform.Android) {
adUnitId = Admob_Android_Interestitial_ID;
} else if(Application.platform == RuntimePlatform.IPhonePlayer){
adUnitId = Admob_iOS_Interestitial_ID;
}
// Initialize an InterstitialAd.
admobInterstitialAd = new InterstitialAd(adUnitId);
// Called when an ad request has successfully loaded.
admobInterstitialAd.AdLoaded += HandleInterstitialAdLoaded;
// Called when an ad request failed to load.
admobInterstitialAd.AdFailedToLoad += HandleInterstitialAdFailedToLoad;
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
admobInterstitialAd.LoadAd(request);
}
public void HandleInterstitialAdLoaded(object sender, EventArgs args)
{
AddLog("Admob Interstitial HandleAdLoaded event received.");
// Handle the ad loaded event.
}
public void HandleInterstitialAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
AddLog("Admob Interstitial Failed to load: " + args.Message);
// Handle the ad failed to load event.
}
#endregion
#region Unity_Ads
private void InitUnityAds() {
string adUnitId = "unexpected_platform";
if (Application.platform == RuntimePlatform.Android) {
adUnitId = Unity_Ads_Android_GAME_ID;
} else if(Application.platform == RuntimePlatform.IPhonePlayer){
adUnitId = Unity_Ads_iOS_GAME_ID;
}
if (Advertisement.isSupported) {
Advertisement.Initialize (adUnitId, false);
} else {
AddLog("Unity Ads Platform not supported");
}
}
private void HandleShowResult (ShowResult result)
{
switch (result)
{
case ShowResult.Finished:
AddLog("Unity Ad was successfully shown.");
break;
case ShowResult.Skipped:
AddLog("Unity Ad was skipped before reaching the end.");
break;
case ShowResult.Failed:
AddLog("Unity Ad failed to be shown.");
break;
}
}
private void HandleRewardedVideoShowResult (ShowResult result)
{
switch (result)
{
case ShowResult.Finished:
AddLog("Unity Rewarded Video Ad was successfully shown.");
if (onRewardedVideoAd != null) {
onRewardedVideoAd(AdStatus.Completed , "Unity Rewarded Video Ad was successfully Completed.");
}
break;
case ShowResult.Skipped:
AddLog("Unity Rewarded Video Ad was skipped before reaching the end.");
if (onRewardedVideoAd != null) {
onRewardedVideoAd(AdStatus.Skipped , "Unity Rewarded Video Ad was skipped before reaching the end.");
}
break;
case ShowResult.Failed:
AddLog("Unity Rewarded Video Ad failed to be shown.");
if (onRewardedVideoAd != null) {
onRewardedVideoAd(AdStatus.Failed , "Unity Rewarded Video Ad failed to be shown.");
}
break;
}
}
#endregion
}
@slowDrag0n
Copy link

buht shukria butt saab 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment