Jump to: navigation, search

Unity

Unity Integration

NoteBubble.png

Important: Please test your integration on a device. Fuse features, including ads, will ONLY work on a device.

NoteBubble.png

Please see this page for a fix to a known bug in Unity which prevents Unity's network calls from working


Downloading the SDK

Before starting integration, you'll need to download the latest version of the Fuse SDK specific to your development environment. You can download the Unity wrapper Here. You can refer to this page for the FuseSDK Code Reference.

Package Importing and Set Up

The Fuse Unity Wrapper is a single unitypackage named FuseUnitySDK.unitypackage

Once you have downloaded it, simply import the package into your Unity project.

Next, create the FuseSDK Prefab by selecting "FuseSDK > Regenerate Prefab" from the menu bar. The prefab will be generated as "Assets/FuseSDK/FuseSDK.prefab". The prefab will have the FuseAPI.cs script attached to it as seen below:

Unity3.PNGFuseSDKPrefab-2.6.1.0.png

Add your APP IDs to the "Android App ID" and/or "iOS App ID" fields of the Fuse SDK component.

Your APP ID is a 36-digit unique ID generated when you add your app to the Fuse Dashboard. It can be found under the title of your app on the dashboard.

Check the “Push Notifications” box to enable the automatic collection of notification tokens. If you have marked your app as being designated for children under the age of 13 (i.e. COPPA compliant), push notifications will not be collected, even if this box is checked. Note that for Android Push Notifications, you must set up GCM, enter your GCM Sender ID to the corresponding field on the component and select "Update Android Manifest" on the FuseSDK menu to generate the necessary entries on the manifest. You can also select the icon to be displayed on push notifications on Android devices on the component.

The Fuse SDK Component also gives you the option to disable logging, and start the session manually.

If you are using Unibill or Prime31 Unity plugins check the corresponding box to enable automatic in-app purchase tracking.

Once you are finished with the prefab configuration, drag and drop the prefab to your scene's hierarchy.

Retrieving App Parameters in Unity Editor and Standalone

The Fuse SDK Component gives you an option to start a Fuse Session (and thus pull down the App Parameters) while in the Unity Editor as well as in Standalone builds. Please note that all other Fuse functionality (including ads) will NOT work.

Using JarResolver

JarResolver is a library for Unity, developed by Google, for managing Google Play Services dependencies. The benefit of JarResolver is that it minimizes conflicts between multiple Unity plugins. It also makes it easier to include the modular Play Services packages and resolve all dependencies between them instead of including the entire Play Services library.

Requirements:

  • Unity 5.0 or higher.
  • The installation of the Android Support Repository and the Google Repository SDK components.

These are found in the "extras" section of the Android SDK Manager.

AndroidSDKManager-PlayServices.png

Usage:

  • Make sure Unity is set to the Android Platform
  • Right click anywhere in the Project view and select Google Play Services > Resolve Client Jars

JarResolverMenu.png

If you are experiencing problems with JarResolver you can remove it and add our dependencies manually. Please note that you will need to manage any conflicts between plugins manually.

  • Delete Assets/PlayServicesResolver
  • Delete Assets/FuseSDK/Editor/FuseSDKDependencies.cs
  • Download Extras/GooglePlayServicesDependencies.zip from the FuseSDKUnity GitHub project
  • Unzip into Assets/Plugins/Android

Using the SDK

Starting a Session

The Fuse SDK Unity wrapper starts the session automatically by default. If you would like to start the session manually, uncheck "Start Session Automatically" on the Fuse SDK Component and call StartSession via script.

The StartSession function is used to bootstrap all communications with the Fuse system. When a session has been established with the Fuse system, the SessionStartReceived callback is called. If a session fails to start, SessionLoginError is called. It is highly recommended to wait for SessionStartReceived before calling any other FuseSDK functions.

    void FuseSDK_SessionStartReceived()
    {
        //Session Start Received
    }
  
    void FuseSDK_SessionLoginError(FuseMisc.FuseError obj)
    {
        //Session Login Error
        print(obj.ToString());
    }

The SessionLoginError callback is called with a FuseError enumerator, which contains the reason the session failed to start. The members of the enumerator and their meanings are as follows:

  • NONE: No error has occurred
  • NOT_CONNECTED: The user is not connected to the internet
  • REQUEST_FAILED: There was an error in establishing a connection with the server.
  • SERVER_ERROR: Data was received, but there was a problem parsing the xml.
  • BAD_DATA: The server has indicated the data it received was not valid.
  • SESSION_FAILURE: The session has recieved an error and the operation did not complete due to this error.
  • INVALID_REQUEST: The request was not valid, and no action will be performed.
  • UNDEFINED: Unknown error.

Registering Callbacks

A script to call the API functions is required. For this example, we will use a C# script.

Register the callbacks on the Awake() function to ensure that they are bound before the session starts:

    void Awake()
    {
        FuseSDK.SessionStartReceived += FuseSDK_SessionStartReceived;
        FuseSDK.SessionLoginError += FuseSDK_SessionLoginError;
  
        FuseSDK.AdAvailabilityResponse += FuseSDK_AdAvailabilityResponse;
        FuseSDK.AdWillClose += FuseSDK_AdWillClose;
        FuseSDK.RewardedAdCompletedWithObject += FuseSDK_RewardedAdCompletedWithObject;
  
        FuseSDK.IAPOfferAcceptedWithObject += FuseSDK_IAPOfferAcceptedWithObject;
        FuseSDK.VirtualGoodsOfferAcceptedWithObject += FuseSDK_VirtualGoodsOfferAcceptedWithObject;
  
        FuseSDK.PurchaseVerification += FuseSDK_PurchaseVerification;
  
        FuseSDK.GameConfigurationReceived += FuseSDK_GameConfigurationReceived;
  
        FuseSDK.NotificationAction += FuseSDK_NotificationAction;
        FuseSDK.NotificationWillClose += FuseSDK_NotificationWillClose;
    }

Complete the script by unregistering actions on OnDestroy():

    void onDestroy()
    {
        FuseSDK.SessionStartReceived -= FuseSDK_SessionStartReceived;
        FuseSDK.SessionLoginError -= FuseSDK_SessionLoginError;
  
        FuseSDK.AdAvailabilityResponse -= FuseSDK_AdAvailabilityResponse;
        FuseSDK.AdWillClose -= FuseSDK_AdWillClose;
        FuseSDK.RewardedAdCompletedWithObject -= FuseSDK_RewardedAdCompletedWithObject;
  
        FuseSDK.IAPOfferAcceptedWithObject -= FuseSDK_IAPOfferAcceptedWithObject;
        FuseSDK.VirtualGoodsOfferAcceptedWithObject -= FuseSDK_VirtualGoodsOfferAcceptedWithObject;
  
        FuseSDK.PurchaseVerification -= FuseSDK_PurchaseVerification;
  
        FuseSDK.GameConfigurationReceived -= FuseSDK_GameConfigurationReceived;
  
        FuseSDK.NotificationAction -= FuseSDK_NotificationAction;
        FuseSDK.NotificationWillClose -= FuseSDK_NotificationWillClose;
    }

Showing Ads

NoteBubble.png

Before your App goes live you must configure your Zones, for more information see Here

Caching Ads

You can use the following function call to fetch an ad, offer, or rewarded video from the given zone and prepare it to be shown;

    void PreloadAd()
    {
        FuseSDK.PreloadAdForZoneID("ZONE ID");
    }
  
    void FuseSDK_AdAvailabilityResponse(bool adAvailable, FuseMisc.FuseError error)
    {
        if (adAvailable)
        {
            //ad available
        }
        else
        {
            //error
            print(error.ToString());
        }
    }

This method is optional and is used to help ensure that an ad is shown in a timely manner. If the zone is not ready to display an ad, this will start loading an appropriate ad but will not show it until ShowAdForZoneID is called. If an ad is ready to be displayed, it does nothing.

Downloading an ad could take several seconds, depending on the size of the ad and connection speed. For best results, you should allow a few seconds for the ad to finish loading (after calling PreloadAdForZoneID) before attempting to show it. When caching is complete through the PreloadAdForZoneID call, an event is raised which indicates whether there is an ad available or not, called AdAvailabilityResponse. You can use this information to set your ad button's state enabled/disabled or visible/hidden.

For example;

  • Placement: Free currency button on the main screen of the game. Recommendation: Preload when the main screen is loaded
  • Placement: Free currency button on the store window. Recommendation: Preload when the store window is selected to load (when the store button is pressed)
  • Placement: Extra life option when the user loses their last life. Recommendation: Preload when the player starts a game with 1 life left.
  • Placement: Non rewarded ad plays before a new level starts. Recommendation: Preload immediately when the current level ends.

You can only cache one zone at a time; if you call this method for more than one zone, the latter calls will overwrite the formerly cached zone.


NoteBubble.png

Please be aware that ad networks require varying amounts of time to initialize. This means that the AdAvailabilityResponse event may return false until the initialization process is complete. We therefore recommend not checking for ad availability immediately after the Fuse session start callback is triggered.


Display Ads

Use the following method for displaying ads;

        //Simple usage. Show the next item in the zone; 
        FuseSDK.ShowAdForZoneID("ZONE ID");

This function attempts to display an ad if one is available. If no ad is immediately ready to display, this function waits up to 3 seconds for an ad to load and displays immediately if loading finishes. AdWillClose callback is always fired at some point after calling this method, either when the ad is closed, or when no ads are loaded before timing out.

        void FuseSDK_AdWillClose()
        {
            //ad will close
        }

Rewarded Ads

You can check whether a zone includes rewarded content or not by calling the ZoneHasRewarded method;

        FuseSDK.ZoneHasRewarded("ZONE ID"); //returns boolean

You can get the information on the reward by calling the GetRewardedInfoForZone method;

        FuseSDK.GetRewardedInfoForZone("ZONE ID"); //returns RewardedInfo

If the ShowAdForZoneID call attempts to display a rewarded ad, by default, an alert will be shown offering the reward to the user, as well as one after the video confirming that they earned the reward. The alerts can be disabled by using the options parameter with the keys FuseMisc.Constants.RewardedAdOptionKey_ShowPreRoll and FuseMisc.Constants.RewardedAdOptionKey_ShowPostRoll using the value false.ToString().

        //Show an ad, disabling the pre roll alert if it is a rewarded video. 
        var ops = new Dictionary<string, string> {
            {FuseMisc.Constants.RewardedAdOptionKey_ShowPreRoll , false.ToString()}}; 
        FuseSDK.ShowAdForZoneID("ZONE ID", ops);

Similarly, the button text on the alerts can be set using the keys FuseMisc.Constants.FuseRewardedOptionKey_PreRollYesButtonText, FuseMisc.Constants.FuseRewardedOptionKey_PreRollNoButtonText, and FuseMisc.Constants.FuseRewardedOptionKey_PostRollContinueButtonText.

        //Show an ad, using custom button text if it is a rewarded video. 
        var ops = new Dictionary<string, string> { 
            {FuseMisc.Constants.RewardedOptionKey_PreRollYesButtonText , "Yes please!"}, 
            {FuseMisc.Constants.RewardedOptionKey_PreRollNoButtonText , "No way!"}, 
            {FuseMisc.Constants.RewardedOptionKey_PostRollContinueButtonText , "SWEET!"}}; 
        FuseSDK.ShowAdForZoneID("ZONE ID", ops); 

If the user should receive a reward, RewardedAdCompletedWithObject will be called.

    void FuseSDK_RewardedAdCompletedWithObject(FuseMisc.RewardedInfo rewardedInfo)
    {
  
    }

RewardedInfo: The RewardedInfo object contains the following;

  • PreRollMessage (string): The message displayed when the reward is offered (before the rewarded video starts playing)
  • RewardMessage (string): The message displayed when the reward is granted (when the rewarded video is completed)
  • RewardItem (string): Rewarded Virtual Currency Type
  • RewardAmount (int): Rewarded Virtual Currency Amount

Once the ad is closed by the user, control will be passed back to the application through the AdWillClose callback method.

IAP and Virtual Good Offers

In-app purchase and Virtual Good offers are created in the Fuse dashboard, and are then assigned to a zone. The following pages provide detailed instructions on how to set up offers in the dashboard:

You can check whether a zone includes IAP or Virtual Goods offers by calling the ZoneHasIAPOffer method and the ZoneHasVirtualGoodsOffer method respectively


        FuseSDK.ZoneHasIAPOffer("ZONE ID"); //returns boolean
        FuseSDK.ZoneHasVirtualGoodsOffer("ZONE ID"); //returns boolean

If you are displaying an ad zone that contains an IAP or Virtual Good offer and the user has accepted an offer, IAPOfferAcceptedWithObject or VirtualGoodsOfferAcceptedWithObject will be called.

    void FuseSDK_IAPOfferAcceptedWithObject(FuseMisc.IAPOfferInfo iapOfferInfo)
    {
  
    }
  
    void FuseSDK_VirtualGoodsOfferAcceptedWithObject(FuseMisc.VGOfferInfo vgOfferInfo)
    {
  
    }

IAPOfferInfo: The IAPOfferInfo object contains the following;

PROPERTY TYPE DESCRIPTION
productID String App store product id used to complete a purchase ex. com.fusepowered.coinpack1
productPrice Integer Price of the IAP (in local currency if available) eg. 2.99, Default 0.
itemAmount Integer Quantity of items being purchased
itemName String The name of the item being purchased.
metadata String Custom metadata that is associated with the offer.
startTime Integer Start date of the offer as a unix epoch (GMT).
endTime Integer End date of the offer as a unix epoch (GMT)

VGOfferInfo: The VGOfferInfo object contains the following;

PROPERTY TYPE DESCRIPTION
purchaseCurrency String The currency used to purchase the offer.
purchasePrice Integer Price of the virtual good.
itemName String The name of the item being purchased.
itemAmount Integer Quantity of items being purchased
currencyID Integer The ID of the currency used for the purchase (as shown in the Fuse dashboard). Required for registering and tracking the purchase of a virtual good.
virtualGoodID Integer The ID of the item (virtual good) being purchased (as shown in the Fuse dashboard). Required for registering and tracking the purchase of a virtual good.
metadata String Custom metadata that is associated with the offer.
startTime Date Start date of the offer as a unix epoch (GMT).
endTime Date End date of the offer as a unix epoch (GMT)

Once the ad is closed by the user, control will be passed back to the application through the AdWillClose callback method.

Tracking In App Purchases

NoteBubble.png

When registering in-app purchases, especially when testing IAP offers, make sure to use a US based iTunes account. Fuse requires USD prices by default, if the purchase is made using another currency it will be available in the Fuse dashboard for setting up targeted IAP offers.

NoteBubble.png

Before your app goes live you must set up Google In-App Purchase Validation via the Fuse dashboard.

IAP-Validation-Android.png

To set up IAP Validation in the Fuse dashboard:

1. From any page in the Fuse dashboard, click on your username in the top right of the upper navigation bar.

2. Choose “Store Credentials” from the dropdown menu

3. Select the “Android” tab

4. In the “IAP Validation” section, click the “GET REFRESH TOKEN” button and follow the instructions

Register IAP Call

Fuse allows tracking of in-app purchases in real-time. The Prime31 and Unibill plugins are both supported to make it easier to automatically track IAPs. Each can be enabled via the FuseSDK prefab component window (see Package Importing and Set Up). If not using a billing plugin, see below for steps to register in-app purchases.

iOS

To register the price and currency that a user is using to make iOS in-app purchases, use the following call:

  FuseSDK.RegisterIOSInAppPurchaseList(products);

After receiving the list of in-app purchases from Apple, this method can be called to record the localized item information.

products Object:

ATTRIBUTE TYPE DESCRIPTION
ProductId String The ID of the product used by the App Store.
Price Float The price of the product.
PriceLocale String The currency of the product's price.


To record an iOS in-app purchase in the Fuse system, use the following call;

        FuseSDK.RegisterIOSInAppPurchase(productId ,transactionId ,transactionReceipt, transactionState);

The parameters of this call are;

  • productId (string): The product ID of the purchased item.
  • transactionId (string): The transaction ID of the purchase supplied by Apple.
  • transactionReceipt (byte[]): The data payload associated with the purchase, supplied by Apple.
  • transactionState (IAPState): The transaction state of the purchase. Members are: PURCHASING, PURCHASED, FAILED, RESTORED.

If your app is using the Prime31 or Unibill plugin you do not need to call these functions!

Android

To record an Android in-app purchase in the Fuse system, make the following call:

  FuseSDK.RegisterAndroidInAppPurchase (purchaseState, purchaseToken, productId, orderId, purchaseTime, developerPayload, price, currency); 		

The parameters of this call are;

  • purchaseState (IAPState): The transaction state of the purchase. Members are: PURCHASED, CANCELED, REFUNDED
  • purchaseToken (string): The purchase token provided by Google Play.
  • productId (string): The product id of the item being purchased.
  • orderId (string): The order id of this transaction.
  • purchaseTime (long): Unix timestamp when purchase was made.
  • developerPayload (string): Developer payload provided by Google Play.
  • price(double): The price of the purchased item.
  • currency (string): The currency string identifier.

This function also has an overload where purchaseTime is of type DateTime.

NoteBubble.png

If your app is using the Prime31 or Unibill plugin you do not need to call these functions! If your app is using the Unity 5+ Purchase API, you need to add Extras/FuseSDK_UnityIAPHelper.cs from our github repository to your project

Purchase Verification

When an in-app purchase is completed and registered, either manually or automatically via a billing plugin, the purchase verification callback will be triggered (note that it must be a registered action, see Registering Callbacks).

This callback will return the verification state, the app store's transaction ID, and the app store's original transaction ID (in the case the purchase is being restored).

The verification states are as follows:

1: The purchase is suspected to be valid.
0: The purchase is suspected to be invalid.
-1: We did not attempt verification. This can be due to a network error or lack of connectivity.

Tracking Virtual Good Purchases

To track Virtual Good Purchases, use the following function call where appropriate:

  FuseSDK.RegisterVirtualGoodsPurchase(int virtualgoodID, int currencyAmount, int currencyID);

Note that “RegisterVirtualGoodsPurchase” is expecting the virtual good ID. This ID is a property of the IAPOfferInfo object (property name: VirtualGoodID), as is the currency ID, that is returned when the VirtualGoodsOfferAcceptedWithObject callback is triggered. These IDs are generated by Fuse when virtual good and items/currencies are added to the dashboard. To find them, select your app in the dashboard, then click the "CONFIGURE" button in the top right. Click the assets tab, and the Virtual Goods sub-tab, and use the IDs as referenced in the table of virtual good entries.

Virtual-goods.png

Tracking Player Events

Player Level

To register a player's level, use the following function call where appropriate:

  FuseSDK.RegisterLevel(int playerLevel);

Currency Balances

The Fuse Event Tracking system can also track 4 different currency balances. To register one of these balances, use the following function call:

  FuseSDK.RegisterCurrency(int currencyIndex,int currencyBalance);

Following registerCurrency should be a number between 1 and 4 corresponding to the currency being tracked.

Birthday

To register a player's birthday, use the following function call where appropriate:

  FuseSDK.RegisterBirthday(int year, int month, int day);

Age

To register a player's age, use the following function call where appropriate:

  FuseSDK.RegisterAge(int age);

Gender

To register a player's gender, use the following function call where appropriate:

  FuseSDK.RegisterGender(int genderIndex);

0 = None

1 = Male

2 = Female

3 = Undecided

4 = Withheld

Parental Consent

To register a player's parental consent status, use the following function call where appropriate:

  FuseSDK.RegisterParentalConsent(bool consent);

Custom Player Events

Custom Player Events are used to track unique information on a per-player basis. Event numbers 1-10 are reserved for integers. To register Custom Player Events with integers, use the following function call where appropriate:

  FuseSDK.RegisterCustomEvent(int eventID,int eventValue);

Event numbers 11-20 are reserved for strings. To register Custom Player Events with strings, use the following function call where appropriate:

  FuseSDK.RegisterCustomEvent(int eventID,string eventValue);

Some examples of things you should not track for custom integer or string-type events:

  • Device or Player IDs
  • Dynamic Variables
  • Emails
  • Account Info

Push Notifications

NoteBubble.png

Please refer to this page to set up GCM before enabling Fuse SDK Push notification features for Android devices.

To enable push notifications, select "Update Android Manifest" from the FuseSDK menu shown below, make sure the Push Notifications option is checked and your GCM Sender ID is entered on the FuseSDK component. The rest will be handled internally by the Fuse SDK Unity Wrapper.
Unity3.PNG