Должен ли объект, который создает рекламу (например, Banner, Interstitial) быть одиночным? - PullRequest
0 голосов
/ 20 июня 2019

Продолжая через Google AdMob читать о реализации для различных объявлений:

https://developers.google.com/admob/unity/banner https://developers.google.com/admob/unity/interstitial

Сейчас у меня есть C # Script, который реализует эти объявления иЯ продолжаю создавать игровой объект внутри моего инспектора, который имеет этот сценарий.

Я считаю, что этого достаточно для того, чтобы я получил простой ответ, надеюсь, без какого-либо кода и очень общего кода.

Я хотел бы знать, следует ли инициализировать этот объект только один раз, в идеале в сцене главного меню, и использовать его в других сценах для управления ссылкой на эти объявления.

ИЛИ

Удалите существующий игровой объект, который управляет этими объявлениями, чтобы затем следующая сцена создавала новую, потенциально показывая рекламу, отличную от предыдущей.

РЕДАКТИРОВАТЬ:

Скрипт AdManager:

using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using GoogleMobileAds.Api;

public class AdManager : MonoBehaviour
{

public static AdManager instance;

//Test id: ca-app-pub-3940256099942544~3347511713
private string APP_ID = "An id";

private BannerView bannerAD;
private InterstitialAd interstitialAD;


private void Awake()
{
    if (instance != null)
    {
        Destroy(gameObject);
    }
    else
    {
        instance = this;
        DontDestroyOnLoad(gameObject);
    }
}



// Start is called before the first frame update
void Start()
{
    //FOR PUBLISHING ONLY
    //MobileAds.Initialize(APP_ID);

    RequestBannerAD();
    RequestInterstitialAD();
}

private void RequestBannerAD()
{
    string banner_ID = "ca-app-pub-3940256099942544/6300978111";
    bannerAD = new BannerView(banner_ID, AdSize.Banner, AdPosition.Bottom);


    // Called when an ad request has successfully loaded.
    bannerAD.OnAdLoaded += HandleOnAdLoaded;
    // Called when an ad request failed to load.
    bannerAD.OnAdFailedToLoad += HandleOnAdFailedToLoad;
    // Called when an ad is clicked.
    bannerAD.OnAdOpening += HandleOnAdOpened;
    // Called when the user returned from the app after an ad click.
    bannerAD.OnAdClosed += HandleOnAdClosed;
    // Called when the ad click caused the user to leave the application.
    bannerAD.OnAdLeavingApplication += HandleOnAdLeavingApplication;

    //FOR PRODUCTION
    //AdRequest adRequest = new AdRequest.Builder().Build();


    //FOR TESTING
    AdRequest adRequest = new AdRequest.Builder().AddTestDevice("2077ef9a63d2b398840261c8221a0c9b").Build();

    bannerAD.LoadAd(adRequest);

     void HandleOnAdLoaded(object sender, EventArgs args)
    {
        Display_Banner();

    }

     void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
    {
        RequestBannerAD();
    }

     void HandleOnAdOpened(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdOpened event received");

    }

     void HandleOnAdClosed(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdClosed event received");

    }

     void HandleOnAdLeavingApplication(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdLeavingApplication event received");
    }
}

public void Display_Banner()
{
    bannerAD.Show();
}


public void DestroyBanner()
{
    bannerAD.Destroy();
}

private void RequestInterstitialAD()
{
    string interstitial_ID = "ca-app-pub-3940256099942544/1033173712";
    interstitialAD = new InterstitialAd(interstitial_ID);


    // Called when an ad request has successfully loaded.
    interstitialAD.OnAdLoaded += HandleOnAdLoaded;
    // Called when an ad request failed to load.
    interstitialAD.OnAdFailedToLoad += HandleOnAdFailedToLoad;
    // Called when an ad is clicked.
    interstitialAD.OnAdOpening += HandleOnAdOpened;
    // Called when the user returned from the app after an ad click.
    interstitialAD.OnAdClosed += HandleOnAdClosed;
    // Called when the ad click caused the user to leave the application.
    interstitialAD.OnAdLeavingApplication += HandleOnAdLeavingApplication;


    //FOR PRODUCTION
    //AdRequest adRequest = new AdRequest.Builder().Build();


    //FOR TESTING
    AdRequest adRequest = new AdRequest.Builder().AddTestDevice("2077ef9a63d2b398840261c8221a0c9b").Build();

    interstitialAD.LoadAd(adRequest);


    void HandleOnAdLoaded(object sender, EventArgs args)
    {

    }

    void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
    {

    }

    void HandleOnAdOpened(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdOpened event received");

    }

    void HandleOnAdClosed(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdClosed event received");

    }

    void HandleOnAdLeavingApplication(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdLeavingApplication event received");
    }
}


public void Display_Interstitial()
{
    if (interstitialAD.IsLoaded())
    {
        interstitialAD.Show();
    }
}


public void DestroyInterstitial()
{
    interstitialAD.Destroy();
}

}

Сценарий MenuLoader (фрагмент к промежуточному вызову, прикрепленный к кнопке пользовательского интерфейса):

public void LoadGameOver()
{
    StartCoroutine(WaitAndLoad_GameOver());
}

private IEnumerator WaitAndLoad_GameOver()
{
    yield return new WaitForSeconds(gameOver_loadDelay);
    FindObjectOfType<AdManager>().Display_Interstitial();
    SceneManager.LoadScene("Game Over");
}

РЕДАКТИРОВАТЬ 2 (в ответ на Eliasar):

06-20 22:07:13.988  6492  6518 E Unity   : NullReferenceException: Object reference not set to an instance of an object
06-20 22:07:13.988  6492  6518 E Unity   :   at AdManager.Display_Banner () [0x00000] in <0b5b8f6032c04370a5fa0fecd73ecd6b>:0 
06-20 22:07:13.988  6492  6518 E Unity   :   at MenuLoader+<WaitAndLoad_Game>d__6.MoveNext () [0x00084] in <0b5b8f6032c04370a5fa0fecd73ecd6b>:0 
06-20 22:07:13.988  6492  6518 E Unity   :   at UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) [0x00027] in <1f017b19aaf9475abf1041405dbaf390>:0 
06-20 22:07:13.988  6492  6518 E Unity   :  

AdManager:

using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using GoogleMobileAds.Api;

public static class AdManager
{

    //public static AdManager instance;

    //Test id: ca-app-pub-3940256099942544~3347511713
    private static string APP_ID = "An id";

    private static BannerView bannerAD;
    private static InterstitialAd interstitialAD;


    //private void Awake()
    //{
    //    if (instance != null)
    //    {
    //        Destroy(gameObject);
    //    }
    //    else
    //    {
    //        instance = this;
    //        DontDestroyOnLoad(gameObject);
    //    }
    //}



    // Start is called before the first frame update
    //void Start()
    //{
    //    //FOR PUBLISHING ONLY
    //    //MobileAds.Initialize(APP_ID);

    //    RequestBannerAD();
    //    RequestInterstitialAD();
    //}

    private static void RequestBannerAD()
    {
        string banner_ID = "ca-app-pub-3940256099942544/6300978111";
        bannerAD = new BannerView(banner_ID, AdSize.Banner, AdPosition.Bottom);


        // Called when an ad request has successfully loaded.
        bannerAD.OnAdLoaded += HandleOnAdLoaded;
        // Called when an ad request failed to load.
        bannerAD.OnAdFailedToLoad += HandleOnAdFailedToLoad;
        // Called when an ad is clicked.
        bannerAD.OnAdOpening += HandleOnAdOpened;
        // Called when the user returned from the app after an ad click.
        bannerAD.OnAdClosed += HandleOnAdClosed;
        // Called when the ad click caused the user to leave the application.
        bannerAD.OnAdLeavingApplication += HandleOnAdLeavingApplication;

        //FOR PRODUCTION
        //AdRequest adRequest = new AdRequest.Builder().Build();


        //FOR TESTING
        AdRequest adRequest = new AdRequest.Builder().AddTestDevice("2077ef9a63d2b398840261c8221a0c9b").Build();

        bannerAD.LoadAd(adRequest);

         void HandleOnAdLoaded(object sender, EventArgs args)
        {
            Display_Banner();

        }

         void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
        {
            RequestBannerAD();
        }

         void HandleOnAdOpened(object sender, EventArgs args)
        {
            MonoBehaviour.print("HandleAdOpened event received");

        }

         void HandleOnAdClosed(object sender, EventArgs args)
        {
            MonoBehaviour.print("HandleAdClosed event received");

        }

         void HandleOnAdLeavingApplication(object sender, EventArgs args)
        {
            MonoBehaviour.print("HandleAdLeavingApplication event received");
        }
    }

    public static void Display_Banner()
    {
        bannerAD.Show();
    }


    public static void DestroyBanner()
    {
        bannerAD.Destroy();
    }

    private static void RequestInterstitialAD()
    {
        string interstitial_ID = "ca-app-pub-3940256099942544/1033173712";
        interstitialAD = new InterstitialAd(interstitial_ID);


        // Called when an ad request has successfully loaded.
        interstitialAD.OnAdLoaded += HandleOnAdLoaded;
        // Called when an ad request failed to load.
        interstitialAD.OnAdFailedToLoad += HandleOnAdFailedToLoad;
        // Called when an ad is clicked.
        interstitialAD.OnAdOpening += HandleOnAdOpened;
        // Called when the user returned from the app after an ad click.
        interstitialAD.OnAdClosed += HandleOnAdClosed;
        // Called when the ad click caused the user to leave the application.
        interstitialAD.OnAdLeavingApplication += HandleOnAdLeavingApplication;


        //FOR PRODUCTION
        //AdRequest adRequest = new AdRequest.Builder().Build();


        //FOR TESTING
        AdRequest adRequest = new AdRequest.Builder().AddTestDevice("2077ef9a63d2b398840261c8221a0c9b").Build();

        interstitialAD.LoadAd(adRequest);


        void HandleOnAdLoaded(object sender, EventArgs args)
        {

        }

        void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
        {

        }

        void HandleOnAdOpened(object sender, EventArgs args)
        {
            MonoBehaviour.print("HandleAdOpened event received");

        }

        void HandleOnAdClosed(object sender, EventArgs args)
        {
            MonoBehaviour.print("HandleAdClosed event received");

        }

        void HandleOnAdLeavingApplication(object sender, EventArgs args)
        {
            MonoBehaviour.print("HandleAdLeavingApplication event received");
        }
    }


    public static void Display_Interstitial()
    {
        if (interstitialAD.IsLoaded())
        {
            interstitialAD.Show();
        }
    }


    public static void DestroyInterstitial()
    {
        interstitialAD.Destroy();
    }


}

MenuLoader (редактирование фрагмента):

public void LoadGameOver()
{
    StartCoroutine(WaitAndLoad_GameOver());
}

private IEnumerator WaitAndLoad_GameOver()
{
    yield return new WaitForSeconds(gameOver_loadDelay);
    AdManager.Display_Interstitial();
    //FindObjectOfType<AdManager>().Display_Interstitial();
    SceneManager.LoadScene("Game Over");
    AdManager.Display_Banner();
}
...