Skip to content

Instantly share code, notes, and snippets.

@xjjon
Created July 23, 2023 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xjjon/b14d1c790e6ab3b2111aee3f6ceee9e8 to your computer and use it in GitHub Desktop.
Save xjjon/b14d1c790e6ab3b2111aee3f6ceee9e8 to your computer and use it in GitHub Desktop.
using System;
using Firebase.Analytics;
using Firebase.Crashlytics;
using UnityEngine;
using UnityEngine.Events;
// Sample Ads Manager for tutorial on integrating ads with Unity using the Mobile Toolkit Plugin (https://assetstore.unity.com/packages/tools/integration/mobile-tools-complete-game-132284?aid=1101l3RjN)
// Full tutorial: https://www.jonathanyu.xyz/unity-tutorials/
public class AdsManager : Monobehaviour
{
protected override void Awake()
{
// Setup GDPR consent
if (!Advertisements.Instance.UserConsentWasSet())
{
// Show prompt to user for GDPR consent and then use the result to set user consent
Advertisements.Instance.SetUserConsent(true);
}
Debug.Log("Initializing Ads");
Advertisements.Instance.Initialize();
}
public bool ShowRewardAd(AdLocation location, UnityAction<bool> onComplete)
{
if (!IsRewardAdReady(location))
{
return false;
}
try
{
Advertisements.Instance.ShowRewardedVideo((status) =>
{
ReportAdCompletionStatus(location, status);
onComplete?.Invoke(status);
});
if (FirebaseManager.Initialized)
{
FirebaseAnalytics.LogEvent("AdStarted", FirebaseAnalytics.ParameterAdUnitName, location.ToString());
}
}
catch (Exception e)
{
Debug.Log("Failed to show ad: " + e.Message);
// Show prompt to user that ad failed to load
if (FirebaseManager.Initialized)
{
Crashlytics.Log($"Rewarded Ad Failed for {location} with {e.Message}");
FirebaseAnalytics.LogEvent("AdFailed", FirebaseAnalytics.ParameterAdUnitName, location.ToString());
}
return false;
}
return true;
}
public void ReportAdCompletionStatus(AdLocation location, bool completed)
{
if (FirebaseManager.Initialized)
{
if (!completed)
{
FirebaseAnalytics.LogEvent("AdSkipped", FirebaseAnalytics.ParameterAdUnitName,
location.ToString());
}
else
{
FirebaseAnalytics.LogEvent("AdCompleted", FirebaseAnalytics.ParameterAdUnitName,
location.ToString());
}
}
}
public bool IsRewardAdReady(AdLocation location)
{
var status = Advertisements.Instance.IsRewardVideoAvailable();
if (FirebaseManager.Initialized && !status)
{
FirebaseAnalytics.LogEvent("AdUnavailable", FirebaseAnalytics.ParameterAdUnitName,
location.ToString());
}
return status;
}
}
// Provides some metadata on where the ad was loaded / shown from. Useful for analytics.
public enum AdLocation
{
Revive, DoubleReward, DailyChest
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment