Native call backs and Monetization of Unity 3d Games for windows phone 8/8.1 platform (Ads and IAP integration)

Posted: November 19, 2014 in Uncategorized

Monetization: Unity 3D Games for windows phone 8/8.1 platform

As per the unity Documentation we can handle the call back using the following techniques as bellow :

1) Writing the custom DLLs (build and run)

2) Event Registration mechanism for unity 3d games.

In this post I would tell you how to handle the event registration and call back handling for native calls. Unity has an option to select the whether you want a C# or C++ project to be generate. In my case i will consider the C#  Xaml project with silverlight runtime.

1) Create a  class which should be always in screen ( keep the DontDestroyOnLoad method in Awake or Start functions)

2) Write the events and register that events in generated code

Ex: see this bellow sample code

public class WINRTInterfaceHandler : MonoBehaviour
{
public delegate void ReceivedCallBack(int miRequestId, string strRequestedData, string result);
public ReceivedCallBack OnCallBack;
string msPrevRequestedData;
int miPrevRequestedId;

private bool isCreated =false;
public event Action<int,string> SendRequestEvent; //Event for handling the call backs

static WINRTInterfaceHandler mInstance = null;
public static WINRTInterfaceHandler Instance
     {
	get{
	if(mInstance == null)
	{
	    GameObject obj = new GameObject();
	    obj.name = "WINRTInterfaceHandler";
            DontDestroyOnLoad(obj);
            mInstance = obj.AddComponent();
        }
 return mInstance;
 }
 }
void Awake()
{
 if(!isCreated)
 {
 DontDestroyOnLoad(this.gameObject); //make sure dont delete at all
 isCreated = true;
 }
 else
 Destroy(this.gameObject);
}
public bool SendRequest(int requestId,string requestedData,ReceivedCallBack requestCallback)
{
 if(requestCallback!= null)
 {
 miPrevRequestedId= requestId;
 msPrevRequestedData= requestedData;
 OnCallBack = requestCallback;
 }

 //depends on request id send the request to native code
 if(SendRequestEvent != null)
 {
 SendRequestEvent(reqType,strData);
 }

} 

public void SendResponse(string msReuestStatus) //which is directly called by the native code
{
 if (OnCallBack == null) //if no call back required then just return
 return;
 else
 ReceivedCallBack temp = OnCallBack;
 OnCallBack = null;
 temp (miPrevRequestedId, msPrevRequestedData, msReuestStatus);
}

}//Class end

Any place in the game code if you can call the any request as follows it will process Syntax:


//If you consider the enums for request id would be nice</pre>
 //syntax:
 WINRTInterfaceHandler.Instance.SendRequest (int id, string sdata, Callback function);

For displaying the ads there in no need to have the call back methods as if want to get the call back pass the call back function as third argument

WINRTInterfaceHandler.Instance.SendRequest (1, "1", OnRecievdCallBack);
WINRTInterfaceHandler.Instance.SendRequest (2, "2", OnRecievdCallBack); 

void OnRecievdCallBack(int reqId, string strRequestedData, string result)
{
if(result=="true")
{
switch(reqId)
{
case 1:
switch(strRequestedData)
{
case "1":
//Give the coins or reward to the user by setting the playerprefs probably
break;
case "2":
break;
}
break;
case 2:
switch(strRequestedData)
{
case "1":
break;
case "2":
break;
}
break;
default:
break;
}
}
else
 {
//Purchase failed don't give any coins and rewards
 }
}

All the setup at unity side is done let’s build the unity project for windows phone platform set the master configuration and rebuild the project. To integrate the Admob ,add the latest version of  GoogleAds sdk  for windows phone 8 and unblock it and add to the references. Now let’s open the MainPage.xaml.cs file Import the GoogleAds As follows: using GoogleAds; and add the InterstitialAd, AdView instances in MainPage Class!

public partial class MainPage : PhoneApplicationPage
{

InterstitialAd interstitialAd;
AdView bannerad;

//Check the following function

private void Unity_Loaded()
{
//here we have to register the send Request event with function of same type

var InterfaceObj = UnityEngine.Object.FindObjectOfType();

if (InterfaceObj != null)
InterfaceObj.SendRequestEvent += OnSendRequest;    //Event Registration for any action at game side

}

private void OnSendRequest(int reqId, string strData)
{
Dispatcher.BeginInvoke(async () =>
{
Switch(reqtype)
{
case 1:
case 2:
{
strData = “someCommonstringID” + strData;
string productId = strData;
if(reqtype == 1)
{
try
{
var licence = Store.CurrentApp.LicenseInformation.ProductLicenses[productId];
if (licence.IsActive)
{
WINRTInterfaceHandler.Instance.Receiver("true");
Store.CurrentApp.ReportProductFulfillment(productId);
}
else
{
await Store.CurrentApp.RequestProductPurchaseAsync(productId, false);

var mproductLicense = Store.CurrentApp.LicenseInformation.ProductLicenses[productId];

if (mproductLicense.IsConsumable && mproductLicense.IsActive)
{
WINRTInterfaceHandler.Instance.Receiver("true");
Store.CurrentApp.ReportProductFulfillment(mproductLicense.ProductId);
}
else if (!mproductLicense.IsConsumable && mproductLicense.IsActive)
{
WINRTInterfaceHandler.Instance.Receiver("true");
}
else
{
WINRTInterfaceHandler.Instance.Receiver("false");
}
}

}
catch{ }
}//consumable goods
else if (reqtype == 2)
{
try
{
if (Store.CurrentApp.LicenseInformation.ProductLicenses[productId].IsActive)
{
WINRTInterfaceHandler.Instance.Receiver("true");
}
else
{
await Store.CurrentApp.RequestProductPurchaseAsync(productId, false);
var licence = Store.CurrentApp.LicenseInformation.ProductLicenses[productId];
if (licence.IsActive)
{
//report product fulfillment is only for consumable items only
WINRTInterfaceHandler.Instance.Receiver("true");
}
else
WINRTInterfaceHandler.Instance.Receiver("false");
}

}
catch
{

}
}//Durable goods
}
Break;
case 3: //Show banner top
case 4: //Show banner bottom
{
try
{
if (bannerad != null && DrawingSurfaceBackground.Children.Contains(bannerad))
{
bannerad.VerticalAlignment = VerticalAlignment.Top; //make it bottom for bottom ads
bannerad.Visibility = Visibility.Visible;
}
else
{
bannerad = new AdView();
bannerad.Format = AdFormats.Banner;
bannerad.VerticalAlignment = VerticalAlignment.Top; //make it bottom for bottom ads
bannerad.AdUnitID = Admob_Banner_Id;
DrawingSurfaceBackground.Children.Add(bannerad);
AdRequest adrequest = new AdRequest();
bannerad.LoadAd(adrequest);
}
}
}
catch
{
}
}
break;
case 5: //Show fullscreen
{
try
{
interstitialAd = new InterstitialAd(Admob_Intenstial_Id);
AdRequest adRequest = new AdRequest();
interstitialAd.ReceivedAd += OnAdReceived;
interstitialAd.LoadAd(adRequest);
}
catch
{
}
}
break;
case 6: //Hide banner top
{
if (bannerad != null && DrawingSurfaceBackground.Children.Contains(bannerad))
{
bannerad.Visibility = Visibility.Collapsed;
}
}
break;
}
private void OnAdReceived(object sender, AdEventArgs e)
{
interstitialAd.ShowAd();
}

Thanks ! PS : This post already published! visit the following ling  Blog 

Advertisements
Comments
  1. […] In my previous post i mentioned about the basic communication between the unity game and native code,Here. […]

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s