Unity ads working in editor but not in build

please help me i am going to publish my game to play store in less then a week
i think the code is working using UnityEngine;
using UnityEngine.Advertisements;
using System.Collections;

public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener
{
[SerializeField] string _androidGameId;
[SerializeField] string _iOSGameId;
[SerializeField] bool _testMode = true; // Set to true for testing; set to false for production
private string _gameId;
[SerializeField] GameObject objectToActivate; // Reference to the GameObject you want to enable/disable

void Awake()
{
    InitializeAds();
}

public void InitializeAds()
{
    // Check if Ads are already initialized or supported before initializing
    if (!Advertisement.isInitialized && Advertisement.isSupported)
    {

#if UNITY_IOS
_gameId = _iOSGameId;
#elif UNITY_ANDROID
_gameId = _androidGameId;
#elif UNITY_EDITOR
_gameId = _androidGameId;
#endif
Advertisement.Initialize(_gameId, _testMode, this);
Debug.Log("Initializing Unity Ads with Game ID: " + _gameId + " in test mode: " + _testMode);
}
else
{
StartCoroutine(ActivateAndDeactivateObject());
Debug.Log(“Unity Ads is already initialized or not supported.”);
}

}
private IEnumerator ActivateAndDeactivateObject()
{
    // Activate the GameObject
    objectToActivate.SetActive(true);
    //Debug.Log("GameObject activated for 2 seconds.");

    // Wait for 2 seconds
    yield return new WaitForSeconds(2f);

    // Deactivate the GameObject
    //objectToActivate.SetActive(false);
    //Debug.Log("GameObject deactivated after 2 seconds.");
}

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

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

}
becous i compeard it to my friends code its almost the same what could be wrong and how can i fix it guys

1 Like

Hello,
To be clear, what exactly is your problem? Please describe more about your issue. Initialization failed? Did you get any error messages?

hey!

sorry for late replay no i do not get any errors.In the editor the test ads just work fine but not in closed testing i tryed both testing mode on and off but still nothing

Hello!

I think I got the same problem. When I’m testing in Unity Editor, everything works fine, Reward ad works every time I want. When I build game and send it to my phone (Android) there are 0 ads. I’m testing and searching for what can cause a problem. And here is my ads initializer code snippet:

public void InitializeAds()
{
#if UNITY_IOS
            _gameId = _iOSGameId;
#elif UNITY_ANDROID
            _gameId = _androidGameId;
#elif UNITY_EDITOR
            _gameId = _androidGameId;
#endif

            if (!Advertisement.isInitialized && Advertisement.isSupported)
            {
                Advertisement.Initialize(_gameId, _testMode, this);
            }
        }

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

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

I’m using Android Logcat and testing with my phone connecting via usb. In the editor I got “Unity Ads initialization complete.” in console log. When I run on android, I got nothing - no “Unity Ads initialization complete” nor “Unity Ads initialization Failed”. I was trying to get some more debug info, and I get this error:

Error Unity Initializing Unity Ads.
Error Unity UnityEngine.Advertisements.Advertisement:CreatePlatform() (at .\Library\PackageCache\com.unity.ads@4.12.0\Runtime\Advertisement\Advertisement.cs:204)
Error Unity UnityEngine.Advertisements.Advertisement:.cctor() (at .\Library\PackageCache\com.unity.ads@4.12.0\Runtime\Advertisement\Advertisement.cs:18)

It looks like something cause a problem in CreatePlatform method. I completly don’t know how can I fix it and what can I do with it. Do you have any solution?

sorry me nether plus i got a new problem the abb file is not building and i cant fix it and am considering switching to admob. please replay if you find the solution.

I think I got it. I mean, I finally have a build where I have an ad on my phone. What I did today what gave me working build:

  1. I removed a library folder, and reopen project to recreate this folder

  2. In the Project Settings → Player → Publishing Settings I checked on:

    • Custom Main Gradle Template
    • Custom Gradle Properties Template
    • Custom Proguard File
  3. In the gradleTemplate.properties I add “android.useAndroidX=true” before “ADDITIONAL_PROPERTIES”

  4. In the mainTemplate.gradle no changes

  5. In the proguard-user.txt I put these: (don’t know if it helps. I found it in some thread on github. When I try only with this, it didn’t worked out. If it would work out without it? Maybe. I’m too tired on this topic to check it today :D)

keep class com.google.unity.** {
   *;
}
-keep public class com.google.android.gms.ads.**{
   public *;
}
-keep public class com.google.ads.**{
   public *;
}
-keepattributes *Annotation*
-dontobfuscate
  1. After this, I did Assets → Mobile Dependency Resolver → Android Resolver → Force Resolve.
  2. After this, I build the game and get ad on my phone. I believe that’s it and it will be working.

I hope it will help!

1 Like

thanks for reaching out i did all the steps and it is working but my dump butt didnt wait untill the ads wear loaded and would click away you really helped me man thanks

Hello dear community!

I’m facing exactly the same problem: I can see the Unity Ads Screen (interstitial) when I run the scene on my Unity Editor (version 2021.3.27f1) but when I run it on my Android and on my iOS devices, I get nothing. On Android, the ad scene never changes but on iOS after a few minutes, it goes to the next game scene (as expected).
I already tried to implement the solution mentioned in this thread (for Android only) but without success.

I will share with you one image of the process I’m following (because as a new user, I can only share 1 image, apparently). But basically, this is the resume of my setup:

01.-Dashboard: I have the correct Game ID for the ad units

02.-Running scene on Unity Editor. As you can see, it seems to have the correct setup:

03.-Still on Unity Editor, after clicking on close or skip ad, it goes to the next game scene (as expected)

04 and 05.-Running on Android device, but only showing an empty screen and it stays there forever

06and 07.-Running on iOS device, as on Android, it shows an empty screen and it stays there for a few minutes, then it goes to the next game scene

08.-Xcode’s console message:

Game State: GameOver
SavingTheMichiGameManager:Update()

Unloading 0 Unused Serialized files (Serialized files now loaded: 0)
UnloadTime: 4.579416 ms
Unloading 126 unused Assets to reduce memory usage. Loaded Objects now: 2338.
Total: 3.831750 ms (FindLiveObjects: 0.225625 ms CreateObjectMapping: 0.093500 ms MarkObjects: 3.341000 ms  DeleteObjects: 0.171209 ms)

Unloading 0 Unused Serialized files (Serialized files now loaded: 0)
UnloadTime: 0.693583 ms
myAdUnitId for iOS = Interstitial_iOS
Inside  if (!Advertisement.isInitialized && Advertisement.isSupported)
AdsInitializer:InitializeAds()

"Log file is at: file:///var/mobile/Containers/Data/Application/C5C9E993-E171-4F05-B270-B6D4EEB54786/Library/Caches/Diagnostic.txt"
đź“‹ LOG ENTRY
System: UnityAds
Level: ℹ️ INFO
Description: Initializing Unity Ads 4.12.3 41203 with game id 5712038 in test mode, session AFE3C2EA-D2A9-497A-8CFA-C67012982DEB

Unloading 2 unused Assets to reduce memory usage. Loaded Objects now: 2326.
Total: 1.039083 ms (FindLiveObjects: 0.072166 ms CreateObjectMapping: 0.032167 ms MarkObjects: 0.920625 ms  DeleteObjects: 0.013792 ms)

"Log file is at: file:///var/mobile/Containers/Data/Application/C5C9E993-E171-4F05-B270-B6D4EEB54786/Library/Caches/Diagnostic.txt"
I/UnityAds: -[USRVInitializeStateConfig startWithCompletion:error:] (line:34) :: 
=============== USRVInitializeStateConfig TSI FLOW/ USING LOADER =============
I/UnityAds: -[USRVConfigurationRequestFactoryWithLogs requestOfType:] (line:25) :: Configuration Request URL: https://configv2.unityads.unity3d.com/webview/4.12.3/release/config.json
I/UnityAds: -[USRVConfigurationRequestFactoryWithLogs requestOfType:] (line:25) :: Configuration Request URL: https://configv2.unityads.unity3d.com/webview/4.12.3/release/config.json
I/UnityAds: -[USRVInitializeStateConfig startWithCompletion:error:]_block_invoke (line:41) :: Config received
From the AdsInitializer script. Unity Ads Initialization Failed: UNKNOWN - Unity Ads WebApp creation failed
AdsInitializer:OnInitializationFailed(UnityAdsInitializationError, String)
UnityEngine.Advertisements.Utilities.CoroutineExecutor:Update()

I tried to implement the Android solution suggested in this discussion but it didn’t work for me. Also, I’d like to ask what it has to be done to also correct the but for my iOS device, I haven’t been able to find a solution for this. I also tried the solution here without success.

Moreover, I was not able to apply the step 6 from Mike’s response ( MikeTrusky). Nevertheless even if I applied the other 5 steps, I was not able to succeed to see the unit ads on my android device.

The code of my scripts is:

AdInitializer:

using UnityEngine;
using UnityEngine.Advertisements;


public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener
{
    [SerializeField] string androidGameId = "RealAndroidIDHere";
    [SerializeField] string iOSGameId = "RealiOSIDHere";
    [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)
        {
            Debug.Log("Inside  if (!Advertisement.isInitialized && Advertisement.isSupported)");

            Advertisement.Initialize(gameId, testMode, this);
        }
    }


    public void OnInitializationComplete()
    {
        Debug.Log("From the AdsInitializer script. Unity Ads initialization complete.");

        FindObjectOfType<AdDisplay>().LoadAd(); // Ensure LoadAd is called after initialization
    }


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

        Loader.Load(Loader.Scene.GameScene);
    }
}

And AdDisplay

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Advertisements;


public class AdDisplay : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField]
    private string iOsAdUnitId = "Interstitial_iOS";
    [SerializeField]
    private string androidAdUnitId = "Interstitial_Android";
    private string adUnitId;
 

    void Awake()
    {
        CheckMobileOS();
    }
 

    private void CheckMobileOS()
    {        
        #if UNITY_IOS
            adUnitId = iOsAdUnitId;
            
            Debug.Log("myAdUnitId for iOS = " + adUnitId);
        #elif UNITY_ANDROID
            adUnitId = androidAdUnitId;
            
            Debug.Log("myAdUnitId for Android = " + adUnitId);
        #else  // then it is UNITY_EDITOR
            adUnitId = androidAdUnitId; // For Testing

            Debug.Log("myAdUnitId for Unity Editor = " + adUnitId);
        #endif
    }


    // 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);
    }
 

    // Show the loaded content in the Ad Unit:
    public void ShowAd()
    {
        // Note that if the ad content wasn't previously loaded, this method will fail
        Debug.Log("Showing Ad: " + adUnitId);
        
        Advertisement.Show(adUnitId, this);
    }
 

    // Implement Load Listener interface methods: 
    public void OnUnityAdsAdLoaded(string adUnitId)
    {
        Debug.Log("Ad successfully loaded: " + adUnitId);
        
        ShowAd();
    }
 

    public void OnUnityAdsFailedToLoad(string _adUnitId, UnityAdsLoadError error, string message)
    {
        Debug.Log($"Error loading Ad Unit: {_adUnitId} - {error.ToString()} - {message}");
        
        // Optionally execute code if the Ad Unit fails to load, such as attempting to try again.
        Loader.Load(Loader.Scene.GameScene);
    }
 

    // Implement Show Listener interface methods: 
    public void OnUnityAdsShowFailure(string _adUnitId, UnityAdsShowError error, string message)
    {
        Debug.Log($"Error showing Ad Unit { _adUnitId }: { error.ToString() } - { message }");

        // Optionally execute code if the Ad Unit fails to show, such as loading another ad.
         Loader.Load(Loader.Scene.GameScene);
    }

 
    public void OnUnityAdsShowStart(string _adUnitId) { }


    public void OnUnityAdsShowClick(string _adUnitId) { }


    public void OnUnityAdsShowComplete(string _adUnitId, UnityAdsShowCompletionState showCompletionState) 
    {
        Debug.Log("Ad completed.");
        
        Loader.Load(Loader.Scene.GameScene);
    }
}

Can you please help me to find a correct answer for this issue, for bot iOS and Android? Thanks in advance for any help.

Kind regards,

Jorge

Thank you, this solved my issue, and my Proguard is disabled, still works