You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何禁用Unity Advertisements的自动初始化功能?

Got it, let's break down how to manually initialize Unity Ads only when you need to show ads—this way you avoid unnecessary network requests and initialization overhead. Here's a practical, step-by-step guide:

1. First, Disable Auto-Initialization

Unity Ads defaults to auto-initializing on app launch, so we need to turn that off first:

  • Go to Edit > Project Settings > Services > Advertisements in the Unity Editor.
  • Uncheck the Enable Auto-Initialization box.
  • Make sure your Game ID (for Android and iOS, if targeting both platforms) is correctly entered here—you can grab these from the Unity Ads dashboard.
2. Build a Centralized Ad Manager

Create a helper class to handle initialization and ad display logic. This keeps your code organized and makes it easy to trigger initialization only when needed. Here's a robust example:

using UnityEngine;
using UnityEngine.Advertisements;

public class AdManager : MonoBehaviour
{
    // Replace these with your actual Game IDs from Unity Ads dashboard
    [SerializeField] private string androidGameId = "YOUR_ANDROID_GAME_ID";
    [SerializeField] private string iosGameId = "YOUR_IOS_GAME_ID";
    [SerializeField] private bool testMode = true; // Keep true during testing, set to false for release

    private bool isAdsInitialized = false;
    public static AdManager Instance { get; private set; }

    private void Awake()
    {
        // Set up singleton for easy global access
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
        }
        else
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
    }

    // Call this method when you're ready to initialize ads (e.g., right before showing an ad)
    public void InitializeAds()
    {
        if (isAdsInitialized)
        {
            Debug.Log("Unity Ads already initialized—skipping.");
            return;
        }

        string targetGameId = Application.platform == RuntimePlatform.IPhonePlayer ? iosGameId : androidGameId;

        // Initialize with optional privacy settings (adjust based on your app's compliance needs)
        var initOptions = new InitializationOptions()
            .SetPrivacyConsentRequired(false); // Set to true if you need to handle GDPR consent first

        Advertisement.Initialize(targetGameId, testMode, initOptions);

        // Listen for initialization success/failure
        Advertisement.add_onInitializationCompleteListener(OnInitializationSuccess);
        Advertisement.add_onInitializationFailedListener(OnInitializationFailed);
    }

    private void OnInitializationSuccess()
    {
        isAdsInitialized = true;
        Debug.Log("Unity Ads initialized successfully!");
    }

    private void OnInitializationFailed(InitializationError error, string message)
    {
        Debug.LogError($"Unity Ads initialization failed: {error} - {message}");
    }

    // Example: Show an interstitial ad (call this when needed, e.g., after a level completes)
    public void ShowInterstitialAd()
    {
        if (!isAdsInitialized)
        {
            Debug.Log("Ads not initialized yet—starting initialization now.");
            InitializeAds();
            // Wait a short time for initialization to finish before retrying
            Invoke(nameof(ShowInterstitialAd), 1.5f);
            return;
        }

        string adUnitId = Application.platform == RuntimePlatform.IPhonePlayer ? "Interstitial_iOS" : "Interstitial_Android";
        if (Advertisement.IsReady(adUnitId))
        {
            Advertisement.Show(adUnitId);
        }
        else
        {
            Debug.Log("Interstitial ad isn't ready yet—try again later.");
        }
    }

    // Example: Show a rewarded ad (call this when user clicks a "Watch Ad for Reward" button)
    public void ShowRewardedAd()
    {
        if (!isAdsInitialized)
        {
            Debug.Log("Initializing ads before showing rewarded ad...");
            InitializeAds();
            Invoke(nameof(ShowRewardedAd), 1.5f);
            return;
        }

        string adUnitId = Application.platform == RuntimePlatform.IPhonePlayer ? "Rewarded_iOS" : "Rewarded_Android";
        if (Advertisement.IsReady(adUnitId))
        {
            var showOptions = new ShowOptions();
            showOptions.resultCallback = HandleRewardedAdResult;
            Advertisement.Show(adUnitId, showOptions);
        }
        else
        {
            Debug.Log("Rewarded ad isn't ready right now.");
        }
    }

    private void HandleRewardedAdResult(ShowResult result)
    {
        switch (result)
        {
            case ShowResult.Finished:
                Debug.Log("User completed the ad—grant reward!");
                // Add your reward logic here (e.g., give coins, unlock level)
                break;
            case ShowResult.Skipped:
                Debug.Log("User skipped the ad—no reward.");
                break;
            case ShowResult.Failed:
                Debug.Log("Ad failed to show.");
                break;
        }
    }
}
3. Trigger Initialization Only When You Need Ads

Now, call the ad methods from your UI or game logic only when necessary. For example:

  • Attach this script to a button that lets users watch an ad for a reward:
using UnityEngine;
using UnityEngine.UI;

public class RewardAdButton : MonoBehaviour
{
    private Button adButton;

    private void Awake()
    {
        adButton = GetComponent<Button>();
        adButton.onClick.AddListener(OnAdButtonClicked);
    }

    private void OnAdButtonClicked()
    {
        AdManager.Instance.ShowRewardedAd();
    }
}

The ShowRewardedAd method will automatically initialize ads if they aren't already set up—so you don't have to call InitializeAds manually every time.

4. Important Tips
  • Test Mode: Don't forget to set testMode = false when you're ready to release your app. Test mode shows dummy ads and prevents your account from being flagged for invalid traffic.
  • Privacy Compliance: If your app targets regions with GDPR or other privacy laws, adjust the SetPrivacyConsentRequired option in initialization. You should get user consent before initializing ads if required.
  • Error Handling: The example includes basic failure listeners, but you can expand this to show user-friendly messages if ads fail to initialize or load.
  • Ad Unit IDs: Make sure your ad unit IDs match exactly what you've created in the Unity Ads dashboard—they're platform-specific, so double-check for Android and iOS.

内容的提问来源于stack exchange,提问作者code_guri

火山引擎 最新活动