Unity/구현

배너 광고를 넣는 법 (Unity)

QuickClid 2025. 5. 13. 22:09
using UnityEngine;
using System;
using GoogleMobileAds;
using GoogleMobileAds.Api;
using UnityEngine.SceneManagement;

public class AdManager : MonoBehaviour
{
    public static GameObject ad_manager;
    private BannerView banner_view;

    private void Awake()
    {
        if (ad_manager == null)
        {
            ad_manager = gameObject;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void Start()
    {
        MobileAds.Initialize((InitializationStatus initStatus) => { }); // Initialize the Google Mobile Ads SDK.
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    private void RequestBanner()
    {
        #if UNITY_ANDROID
            string _adUnitId = "ca-app-pub-3940256099942544/6300978111";
        #elif UNITY_IPHONE
            string _adUnitId = "ca-app-pub-3940256099942544/2934735716";
        #else
            string _adUnitId = "unused";
        #endif

        //Clean up banner ad before creating a new one.
        if (banner_view != null)
        {
            banner_view.Destroy();
        }

        // Create a adaptively-sized banner at top of the screen
        AdSize adaptiveSize = AdSize.GetCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(AdSize.FullWidth);
        banner_view = new BannerView(_adUnitId, adaptiveSize, AdPosition.Bottom);

        // create our request used to load the ad.
        var adRequest = new AdRequest();

        // send the request to load the ad.
        banner_view.LoadAd(adRequest); //Debug.Log("Loading banner ad.");
    }

    private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        if (scene.name == "AD Scene")
        {
            RequestBanner();
        }
        else
        {
            if (banner_view != null)
            {
                banner_view.Destroy();
            }
        }
    }
}