Установите, когда должна отображаться промежуточная реклама Chartboost

Каким-то образом мне нужно установить, что мое промежуточное объявление Chartboost будет отображаться, когда я захочу, потому что оно просто всплывает случайно (даже в самой игре, когда игрок играет). Я пытаюсь сделать это в UNITY3D в C#.

В моем CBScript.cs есть код, который в основном содержит всю необходимую информацию для загрузки моих объявлений из Chartboost. Я добавил этот скрипт в мой пустой GameObject в моем представлении Hierarchy.

CBScript.cs:

    using UnityEngine;
    using System.Collections;
    using System;
    using Chartboost;


    public class CBScript : MonoBehaviour {

        #if UNITY_ANDROID || UNITY_IPHONE

        public void Update() {
            #if UNITY_ANDROID
            // Handle the Android back button (only if impressions are set to not use activities)
            if (Input.GetKeyUp(KeyCode.Escape)) {
                // Check if Chartboost wants to respond to it
                if (CBBinding.onBackPressed()) {
                    // If so, return and ignore it
                    return;
                } else {
                    // Otherwise, handle it ourselves -- let's close the app
                    Application.Quit();
                }
            }
            #endif
        }

        void OnEnable() {
            // Initialize the Chartboost plugin
            #if UNITY_ANDROID
            // Replace these with your own Android app ID and signature from the Chartboost web portal
            CBBinding.init("ID", "Signature");
            #elif UNITY_IPHONE
            // Replace these with your own iOS app ID and signature from the Chartboost web porta

l
        CBBinding.init("ID", "Signature");
        #endif
    }

    void OnApplicationPause(bool paused) {
        #if UNITY_ANDROID
        // Manage Chartboost plugin lifecycle
        CBBinding.pause(paused);
        #endif
    }

    void OnDisable() {
        // Shut down the Chartboost plugin
        #if UNITY_ANDROID
        CBBinding.destroy();
        #endif
    }
    // UNITY_ANDROID || UNITY_IPHONE
    #endif
}

А теперь я собираюсь показать вам, ребята, как я реализовал этот код для одной из моих игровых функций. Я действительно хочу, чтобы моя промежуточная реклама Chartboost появлялась после того, как игрок проигрывает и появляется экран "Игра закончена". Так что это фрагмент из моего скрипта GUI, функция ShowEnd:

//Shows the end menu after a crash
    public void ShowEnd()
    {
        //Save the mission and activate the finish menu
        MissionManager.Instance.Save();
        EnableDisable(finishMenu, true);

        //Get the current coin and distance data
        int currentDist = (int)LevelGenerator.Instance.distance;
        int currentCoins = LevelManager.Instance.Coins();

        //Apply the data to the finish menu
        finishTexts[0].text = currentDist + "M";
        finishTexts[1].text = currentCoins.ToString();

        //If the current distance is greater than the best distance
        if (currentDist > SaveManager.GetBestDistance())
            //Set the current distance as the best distance
            SaveManager.SetBestDistance(currentDist);

        //Add the collected coins to the account
        SaveManager.SetCoins(SaveManager.GetCoins() + currentCoins);

        //Show the finish menu
        StartCoroutine(FadeScreen(0.4f, 0.7f));
        StartCoroutine(MoveMenu(finishMenu.transform, 0, -14.8f, 0.55f, false));

        OnGUI ();

    }

А это OnGUI(); функция, которая ловит и фактически показывает промежуточную рекламу:

void OnGUI(){
        #if UNITY_ANDROID
        // Disable user input for GUI when impressions are visible
        // This is only necessary on Android if we have disabled impression activities
        //   by having called CBBinding.init(ID, SIG, false), as that allows touch
        //   events to leak through Chartboost impressions
        GUI.enabled = !CBBinding.isImpressionVisible();
        #endif

        GUI.matrix = Matrix4x4.Scale(new Vector3(2, 2, 2));
        CBBinding.cacheInterstitial("Default");
        CBBinding.showInterstitial("Default");
    }

Как я уже сказал, CB Interstitial Ads показывается в случайном порядке. Я хочу, чтобы мое объявление показывалось только сразу после экрана Game Over. Я знаю, что сейчас все делаю неправильно, но я не знаю, как это исправить. Спасибо и ценим.

1 ответ

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

void OnEnable() {
    CBBinding.cacheInterstitial("Default");
}

А внутри функции OnGUI () вы должны сначала проверить наличие вставки, а затем вызвать showInterstitial()

void OnGUI(){
        #if UNITY_ANDROID
        // Disable user input for GUI when impressions are visible
        // This is only necessary on Android if we have disabled impression activities
        //   by having called CBBinding.init(ID, SIG, false), as that allows touch
        //   events to leak through Chartboost impressions
        GUI.enabled = !CBBinding.isImpressionVisible();
        #endif

        GUI.matrix = Matrix4x4.Scale(new Vector3(2, 2, 2));
        if (CBBinding.hasInterstitial("Default"))
            CBBinding.showInterstitial("Default");
    }
Другие вопросы по тегам