‹ UnityAds Doc Home

UnityAds Integration Guide

For the C++ version of cocos2d-x v3.x - (all other versions)

SDK Version

Integration

Open a terminal and use the following command to install the SDKBOX UnityAds plugin. Make sure you setup the SDKBOX installer correctly.

$ sdkbox import unityads

Important Notice

Please make sure the following settings in your project to make the plugin work well.

Disable App Transport Security

Adding the following entry to the info.plist file:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

It should look like this:

Disable Bitcode support

You have to turn off Bitcode support. If you don't, cocos2d-x will fail to build.

Set your game requires full screen

If your game doesn't support all screen orientations, you will need to check Requires full screen in Xcode. If you do not, your app will fail Apple's submission process.

Whitelist canOpenURL function

This setting depends on what plugins are in your project. You may need to add the required entry to the info.plist, under LSApplicationQueriesSchemes.

JSON Configuration

SDKBOX Installer will automatically inject a sample configuration to your res/sdkbox_config.json, that you have to modify it before you can use it for your own app

Here is an example of the UnityAds configuration, you need to replace <gameId> item with your specific UnityAds account information.

"UnityAds":{
    "gameId": "1493045",
    "testMode": true,
    "ads": {
        "banner": {
            "placement": "banner",
            "type":"banner"
        },
        "interstitial1": {
            "placement": "video"
        },
        "interstitial2": {
            "placement": "rewarded_video"
        },
    }
}

If you want to display the banner, you need to configure banner information in the ads in sdkbox_config.json. Interstitial can also be configured in ads. This is not mandatory, but it is recommended.

Usage

Initialize UnityAds

Initialize the plugin where appropriate in your code. We recommend to do this in the AppDelegate::applicationDidFinishLaunching() or AppController:didFinishLaunchingWithOptions(). Make sure to include the appropriate headers:

#include "PluginUnityAds/PluginUnityAds.h"
AppDelegate::applicationDidFinishLaunching()
{
     sdkbox::PluginUnityAds::init();
}

Show Ads

After initialization you can begin to use the UnityAds functionality:


std::string ad = "";
if (sdkbox::PluginUnityAds::isReady(ad)) {
    sdkbox::PluginUnityAds::show(ad);
} else {
    CCLOG("unityads is not ready");
}

Catch UnityAds events (optional)

This allows you to catch the UnityAds events so that you can perform operations based upon responses. A simple example might look like this:

#include "PluginUnityAds/PluginUnityAds.h"
class MyClass : public sdkbox::UnityAdsListener {
public:

    void unityAdsDidClick(const std::string& placementId) {
        CCLOG("unityads click %s", placementId.c_str());
    }

    void unityAdsPlacementStateChanged(const std::string& placementId,
                                PluginUnityAds::SBUnityAdsPlacementState oldState,
                                PluginUnityAds::SBUnityAdsPlacementState newState) {
        CCLOG("unityads state change %s %d->%d", placementId.c_str(), oldState, newState);
    }

    void unityAdsReady(const std::string& placementId) {
        CCLOG("unityads ready %s", placementId.c_str());
    }

    void unityAdsDidError(sdkbox::PluginUnityAds::SBUnityAdsError error, const std::string& message) {
        CCLOG("unityads error %d %s", error, message.c_str());
    }

    void unityAdsDidStart(const std::string& placementId) {
        CCLOG("unityads start %s", placementId.c_str());
    }

    void unityAdsDidFinish(const std::string& placementId, sdkbox::PluginUnityAds::SBUnityAdsFinishState state) {
        CCLOG("unityads finish %d %s", state, placementId.c_str());
    }

};
sdkbox::PluginUnityAds::setListener(this);

SDKBoxAds

You can use SDKBoxAds api to display AdMob ads. Also need to update your sdkbox_config.json:

    {
        "android": {
            "SdkboxAds": {
                "units": [
                    "UnityAds" // Add Ad mediations, ["AdColony", "AdMob", "Chartboost", "Appnext", "UnityAds"]
                ],
                "placements": [
                    {
                        "id": "placement-admob", // ad group name
                        "strategy": "round-robin", // ["round-robin", "weight"]
                        "units": [
                            {
                                "unit": "UnityAds", // Mediation name
                                "name": "video" // Ad name, comes from "AdMob" ads section
                            }
                        ]
                    }
                ]
            }
        },
        "ios": {
            "SdkboxAds": {
                "debug": true,
                "units": [
                    "UnityAds"
                ],
                "placements": [
                    {
                        "id": "ads1",
                        "strategy": "round-robin",
                        "units": [
                            {
                                "unit": "UnityAds",
                                "name": "video"
                            }
                        ]
                    }
                ]
            }
        }
    }

SDKBoxAds Core API

check ads available

sdkbox::PluginSdkboxAds::isAvailable(placementName)
// sdkbox::PluginSdkboxAds::isAvailable("ads1")

show the ads

sdkbox::PluginSdkboxAds::placement(placementName)
// sdkbox::PluginSdkboxAds::placement("ads1")

API Reference

Methods

static bool init ( ) ;

initialize the plugin instance.

static void setListener ( UnityAdsListener * listener ) ;

Set listener to listen for inmobi events

static UnityAdsListener * getListener ( ) ;

Get the listener

static void removeListener ( ) ;

Remove the listener, and can't listen to events anymore

static bool isSupported ( ) ;
static bool isReady ( const std::string & placementId ) ;
static void show ( const std::string & placementId ) ;
static SBUnityAdsPlacementState getPlacementState ( const std::string & placementId ) ;
static void setGDPR ( bool enabled ) ;

Enable GDPR

static void setServerId ( const std::string & sid ) ;

Listeners

void unityAdsDidClick ( const std::string & placementId ) 
void unityAdsPlacementStateChanged ( const std::string & placementId ,
                                     PluginUnityAds::SBUnityAdsPlacementState oldState ,
                                     PluginUnityAds::SBUnityAdsPlacementState newState ) 
void unityAdsReady ( const std::string & placementId ) 
void unityAdsDidError ( PluginUnityAds::SBUnityAdsError error ,
                        const std::string & message ) 
void unityAdsDidStart ( const std::string & placementId ) 
void unityAdsDidFinish ( const std::string & placementId ,
                         PluginUnityAds::SBUnityAdsFinishState state ) 

Manual Integration

If the SDKBOX Installer fails to complete successfully, it is possible to integrate SDKBOX manually. If the installer complete successfully, please do not complete anymore of this document. It is not necessary.

These steps are listed last in this document on purpose as they are seldom needed. If you find yourself using these steps, please, after completing, double back and re-read the steps above for other integration items.

Manual Integration For iOS

Drag and drop the following frameworks from the plugins/ios folder of the UnityAds bundle into your Xcode project, check Copy items if needed when adding frameworks:

sdkbox.framework

PluginUnityAds.framework

UnityAds.framework

Manual Integration For Android

SDKBOX supports three different kinds of Android projects command-line, eclipse and Android Studio.

Copy Files

Copy the following jar files from plugin/android/libs folder of this bundle into your project's /libs folder.

unity-ads.jar

PluginUnityAds.jar

sdkbox.jar

Copy jni libs

Copy and overwrite all the folders from plugin/android/jni to your <project_root>/jni/ directory.

Edit AndroidManifest.xml

<!--Mandatory permissions to receive ads-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<activity
    android:name="com.unity3d.ads.adunit.AdUnitActivity"
    android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen"
    android:hardwareAccelerated="true"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen" />
<activity
    android:name="com.unity3d.ads.adunit.AdUnitSoftwareActivity"
    android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen"
    android:hardwareAccelerated="false"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen" />

Edit Android.mk

Edit <project_root>/jni/Android.mk to:

Add additional requirements to LOCAL_WHOLE_STATIC_LIBRARIES:

LOCAL_WHOLE_STATIC_LIBRARIES += PluginUnityAds
LOCAL_WHOLE_STATIC_LIBRARIES += sdkbox

Add a call to:

$(call import-add-path,$(LOCAL_PATH))

before any import-module statements.

Add additional import-module statements at the end:

$(call import-module, ./sdkbox)
$(call import-module, ./pluginunityads)

This means that your ordering should look similar to this:

$(call import-add-path,$(LOCAL_PATH))
$(call import-module, ./sdkbox)
$(call import-module, ./pluginunityads)

Note: It is important to make sure these statements are above the existing $(call import-module,./prebuilt-mk) statement, if you are using the pre-built libraries.

Modify Application.mk (Cocos2d-x v3.0 to v3.2 only)

Edit <project_root>/jni/Application.mk to make sure APP_STL is defined correctly. If Application.mk contains APP_STL := c++_static, it should be changed to:

APP_STL := gnustl_static

Modify AppActivity.java

Plugin >= 2.4.0.3

  1. Find the AppActivity.java
find . -name "AppActivity.java"
  1. Replace extends Cocos2dxActivity with extends com.sdkbox.plugin.SDKBoxActivity

Example of the directory where the AppActivity.java file is located:

cpp
  - proj.android/src/org/cocos2dx/cpp/AppActivity.java
  - proj.android-studio/app/src/org/cocos2dx/cpp/AppActivity.java
  - proj.android/app/src/org/cocos2dx/cpp/AppActivity.java ( from cocos2d-x 3.17)

lua
  - frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/AppActivity.java
  - frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/lua/AppActivity.java
  - frameworks/runtime-src/proj.android/app/src/org/cocos2dx/lua/AppActivity.java (from cocos2d-x 3.17)

js
  - frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java
  - frameworks/runtime-src/proj.android/app/src/org/cocos2dx/javascript/AppActivity.java ( from cocos2d-x 3.17)

Plugin < 2.4.0.3

Note: When using Cocos2d-x from source, different versions have Cocos2dxActivity.java in a different location. One way to find the location is to look in proj.android/project.properties. Example: android.library.reference.1=../../cocos2d-x/cocos/platform/android/java

In this case, Cocos2dxActivity.java should be located at:

../../cocos2d-x/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java
import android.content.Intent;
import com.sdkbox.plugin.SDKBox;
onLoadNativeLibraries();
SDKBox.init(this);
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if(!SDKBox.onActivityResult(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
          }
    }
    @Override
    protected void onStart() {
          super.onStart();
          SDKBox.onStart();
    }
    @Override
    protected void onStop() {
          super.onStop();
          SDKBox.onStop();
    }
    @Override
    protected void onResume() {
          super.onResume();
          SDKBox.onResume();
    }
    @Override
    protected void onPause() {
          super.onPause();
          SDKBox.onPause();
    }
    @Override
    public void onBackPressed() {
          if(!SDKBox.onBackPressed()) {
            super.onBackPressed();
          }
    }

Proguard (optional)

proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# unityads
# Keep filenames and line numbers for stack traces
-keepattributes SourceFile,LineNumberTable

# Keep JavascriptInterface for WebView bridge
-keepattributes JavascriptInterface

# Sometimes keepattributes is not enough to keep annotations
-keep class android.webkit.JavascriptInterface {
   *;
}

# Keep all classes in Unity Ads package
-keep class com.unity3d.ads.** {
   *;
}


# cocos2d-x
-keep public class org.cocos2dx.** { *; }
-dontwarn org.cocos2dx.**
-keep public class com.chukong.** { *; }
-dontwarn com.chukong.**

# google play service
-keep public class com.google.android.gms.** { public *; }
-dontwarn com.google.android.gms.**

-keep class com.google.protobuf.** { *; }
-dontwarn com.google.protobuf.**

-keep class * extends java.util.ListResourceBundle {
    protected Object[][] getContents();
}

-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
    public static final *** NULL;
}

-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
    @com.google.android.gms.common.annotation.KeepName *;
}

-keepnames class * implements android.os.Parcelable {
    public static final ** CREATOR;
}

#sdkbox
-keep public class com.sdkbox.** { *; }
-dontwarn com.sdkbox.**

Note: Proguard only works with Release builds (i.e cocos run -m release) debug builds do not invoke Proguard rules.