在 Unity 中初始化 SDK
要初始化 SDK,您必须引用项目的游戏 ID 以对应相应的平台。您可以从 Unity Ads Monetization 仪表盘 中找到游戏 ID,方法是选择 Monetization 套件,导航到您当前的项目,然后在二级导航栏中选择 Settings,并滚动到 Game IDs 部分。
Note: Starting from SDK version 4.4.1, the Unity Ads package is now called the Advertisement Legacy package in the Unity Editor. The Advertisement Legacy package version 4.12 is still functional but will not receive any further updates for new or enhanced features. SDK version 4.12 supports the Apple Privacy Manifest update, with no further updates planned for the package.
在您的游戏脚本头文件中,包含 UnityEngine.Advertisements
命名空间。在游戏运行时生命周期的早期阶段初始化 SDK,最好在启动时使用 Initialize
函数。在 SDK 版本 3.7.0 及更高版本中,您可以使用 IUnityAdsInitializationListener
回调来接收初始化完成时的通知,或者在发生错误时接收详细信息。
using UnityEngine;
using UnityEngine.Advertisements;
public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener
{
[SerializeField] string _androidGameId;
[SerializeField] string _iOSGameId;
[SerializeField] bool _testMode = true;
private string _gameId;
void Awake()
{
InitializeAds();
}
public void InitializeAds()
{
#if UNITY_IOS
_gameId = _iOSGameId;
#elif UNITY_ANDROID
_gameId = _androidGameId;
#elif UNITY_EDITOR
_gameId = _androidGameId; //Only for testing the functionality in the Editor
#endif
if (!Advertisement.isInitialized && Advertisement.isSupported)
{
Advertisement.Initialize(_gameId, _testMode, 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}");
}
}
下一步:要继续集成,请参阅 在 Unity 中实现基本广告 文档。