Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
846 views
in Technique[技术] by (71.8m points)

c# - Unity - Admob hide banner doesn't work

Why doesn't my admob banner hide when I go the next scene called ''Main''? I did everything what other people said on other threads..

This is my code:

using GoogleMobileAds.Api;  

public class AdmobAds : MonoBehaviour {

private BannerView bannerView;


    private void RequestBanner()
    {
        #if UNITY_ANDROID
        string adUnitId = "ca-app-pub-xxxxxxxxxxxxxxxxxx";
        #elif UNITY_IPHONE
        string adUnitId = "INSERT_IOS_BANNER_AD_UNIT_ID_HERE";
        #else
        string adUnitId = "unexpected_platform";
        #endif

        // Create a 320x50 banner at the top of the screen.
        BannerView bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Bottom);
        // Create an empty ad request.
        AdRequest request = new AdRequest.Builder().Build();
        // Load the banner with the request.
        bannerView.LoadAd(request);
    }

    public void HideAd()
    {
        bannerView.Destroy ();
        bannerView.Hide ();
    }

    void Start()
    {
        Scene currentScene = SceneManager.GetActiveScene ();
        string sceneName = currentScene.name;

        if (sceneName == "Menu") 
        {
            RequestBanner ();
        }

        else if (sceneName == "Main") 
        {
            bannerView.Destroy ();
            bannerView.Hide ();
        }
    }
}

Also the ''public void HideAd'' is attachted to the start button, still it doesn't hide the banner..

What do I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is in the RequestBanner function:

BannerView bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Bottom);

The bannerView is a local variable and the new BannerView instance will be stored to that local bannerView variable instead of the global bannerView variable.

You need that BannerView instance to be stored in the global bannerView variable.

That should be changed to:

bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Bottom);

Another problem is here:

public void HideAd()
{
    bannerView.Destroy ();
    bannerView.Hide ();
}

You are destroying bannerView before hiding it. It should be the other way around. You should Hide then Destroy the bannerView. If fact, simply Hiding the bannerView should be fine. You don't have to Destroy it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...