Unity-Add ads to your project in the game-UnityAds

foreword

Here choose to use UnityAds to add available ads to your project

Why choose UnityAds: 

First of all, Unity has officially added advertisements that can be used locally in China, which means that there is no need for a ladder to browse advertisements. Secondly, the process of adding advertisements inside Unity is extremely simple, and can basically be solved in a few steps. This component comes with it, and there is no need for troublesome external imports

process

The general process is divided into 3 steps

1. Load the ad component

2. Set up your own ad account ID

3. Implement the ad loading process

First, there are two ways to load ad components:

1. Click Ctrl+0 in unity to quickly open the page

2. Search Advertisement in UnityPackageManager and import components

First you need an account, register your account and advertising ID in the link below

Unity Gaming Services

After registering, go to this page:

Among them, GameId is the ID you need to initialize, which is the ID of the game to connect to your account

The following are three types of ads, normal, incentive and banner ads, here we choose incentive ads as a test 

The official documentation describes it very clearly, here is just the code copied from the official documentation

Unity Ads SDK API reference

Example use:

using UnityEngine;
using UnityEngine.Advertisements;

public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener
{
	[SerializeField] string _androidGameId;
	[SerializeField] string _iOsGameId;
	[SerializeField] bool _testMode = true;
	[SerializeField] bool _enablePerPlacementMode = true;
	private string _gameId;

	void Awake()
	{
		InitializeAds();
	}

	public void InitializeAds()
	{
		_gameId = (Application.platform == RuntimePlatform.IPhonePlayer)
			? _iOsGameId
			: _androidGameId;
		Advertisement.Initialize(_gameId, _testMode, _enablePerPlacementMode, this);
	}

	public void OnInitializationComplete()
	{
		Debug.Log("Unity Ads initialization complete.");
	}

	public void OnInitializationFailed(UnityAdsInitializationError error, string message)
	{
		Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
	}


}

 

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;
using System.Collections;
public class RewardedAdsButton : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
	[SerializeField] Button _showAdButton;
	[SerializeField] string _androidAdUnitId = "Rewarded_Android";
	[SerializeField] string _iOsAdUnitId = "Rewarded_iOS";
	public Text text;
	string _adUnitId;

	void Awake()
	{
		// Get the Ad Unit ID for the current platform:
		_adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
			? _iOsAdUnitId
			: _androidAdUnitId;

		//Disable button until ad is ready to show
		//_showAdButton.interactable = false;
	}
	IEnumerator Load()
	{
		while (true)
		{
			if (!Advertisement.IsReady(_adUnitId))
			{
				LoadAd();
			}
			yield return new WaitForSeconds(20f);
		}
	}
	private void Start()
	{

		_showAdButton.onClick.AddListener(ShowAd);
		StartCoroutine(Load());
	}

	// Load content to the Ad Unit:
	public void LoadAd()
	{
		// IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
		Debug.Log("Loading Ad: " + _adUnitId);
		Advertisement.Load(_adUnitId, this);
		//Invoke(nameof(ShowAd), 1f);
	}

	// If the ad successfully loads, add a listener to the button and enable it:
	public void OnUnityAdsAdLoaded(string adUnitId)
	{
		Debug.Log("Ad Loaded: " + adUnitId);

		if (adUnitId.Equals(_adUnitId))
		{
			// Configure the button to call the ShowAd() method when clicked:
			_showAdButton.onClick.AddListener(ShowAd);
			// Enable the button for users to click:
			_showAdButton.interactable = true;
		}
	}

	// Implement a method to execute when the user clicks the button.
	public void ShowAd()
	{
		if (!Advertisement.IsReady(_adUnitId))
		{
			LoadAd();
		}
		//_showAdButton.interactable = false;
		ShowOptions options = new ShowOptions { resultCallback = HandleShowResult };
		//Advertisement.Show("rewardedVideo", options);
		// Disable the button: 
		// Then show the ad:
		Advertisement.Show(_adUnitId, options);
		//print();

	}

	private void HandleShowResult(ShowResult result)
	{
		_showAdButton.interactable = true;
		switch (result)

		{

			//广告看完

			case ShowResult.Finished:
				print("广告加载成功");
				text.text = "Success";
				//广告看完了,给玩家奖励
				break;
			//跳过广告
			case ShowResult.Skipped:
				print("广告完全加载成功了吗啊");
				text.text = "Failed";
				break;
			case ShowResult.Failed:
				text.text = "Failed";
				print("广告完全加载成功了吗啊");
				break;

		}

	}

	// Implement the Show Listener's OnUnityAdsShowComplete callback method to determine if the user gets a reward:
	public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
	{
		if (adUnitId.Equals(_adUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
		{
			Debug.Log("Unity Ads Rewarded Ad Completed");
			// Grant a reward.

			// Load another ad:
			Advertisement.Load(_adUnitId, this);

			text.text = "SUccess";
			print("广告完全加载成功了吗啊");
		}
	}

	// Implement Load and Show Listener error callbacks:
	public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
	{

		Debug.Log($"Error loading Ad Unit {adUnitId}: {error.ToString()} - {message}");
		// Use the error details to determine whether to try to load another ad.
	}

	public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
	{
		text.text = "Failed";
		Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
		// Use the error details to determine whether to try to load another ad.
	}

	public void OnUnityAdsShowStart(string adUnitId) { text.text = "Strt"; }
	public void OnUnityAdsShowClick(string adUnitId) { text.text = "Click"; }

	void OnDestroy()
	{
		// Clean up the button listeners:
		_showAdButton.onClick.RemoveAllListeners();
	}
}

Mount the two scripts, enter the GameID and then add the Button button to use it directly 

Guess you like

Origin blog.csdn.net/qq_55042292/article/details/125458225