Friday, 5 September 2014

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

Monetization: Unity 3D Games for windows phone 8/8.1 platform
As per the unity 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;
public event Action<int,string> SendRequestEvent; //Event for handling the call backs
private bool isCreated =false; static WINRTInterfaceHandler mInstance = null;
GameObject obj = new GameObject();
public static WINRTInterfaceHandler Instance { get{ if(mInstance == null) {
}
obj.name = "WINRTInterfaceHandler"; DontDestroyOnLoad(obj); mInstance = obj.AddComponent();
DontDestroyOnLoad(this.gameObject); //make sure dont delete at all
return mInstance; } } void Awake() { if(!isCreated) { isCreated = true; } else Destroy(this.gameObject); }
miPrevRequestedId= requestId;
public bool SendRequest(int requestId,string requestedData,ReceivedCallBack requestCallback) { if(requestCallback!= null) { msPrevRequestedData= requestedData; OnCallBack = requestCallback; }
public void SendResponse(string msReuestStatus) //which is directly called by the native code
//depends on request id send the request to native code if(SendRequestEvent != null) { SendRequestEvent(reqType,strData); } } { 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) {
//Give the coins or reward to the user by setting the playerprefs probably
case "1": break; case "2": break; } break; case 2: switch(strRequestedData) {
//Purchase failed don't give any coins and rewards
case "1": break; case "2": break; } break; default: break; } } else { } }
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;
private void Unity_Loaded()
//Check the following function {
var InterfaceObj = UnityEngine.Object.FindObjectOfType();
//here we have to register the send Request event with function of same type if (InterfaceObj != null)
private void OnSendRequest(int reqId, string strData)
InterfaceObj.SendRequestEvent += OnSendRequest;    //Event Registration for any action at game side } { Dispatcher.BeginInvoke(async () => { Switch(reqtype) { case 1: case 2: {
WINRTInterfaceHandler.Instance.Receiver("true");
strData = “someCommonstringID” + strData; string productId = strData; if(reqtype == 1) { try { var licence = Store.CurrentApp.LicenseInformation.ProductLicenses[productId]; if (licence.IsActive) {
if (mproductLicense.IsConsumable && mproductLicense.IsActive)
Store.CurrentApp.ReportProductFulfillment(productId); } else { await Store.CurrentApp.RequestProductPurchaseAsync(productId, false); var mproductLicense = Store.CurrentApp.LicenseInformation.ProductLicenses[productId]; {
WINRTInterfaceHandler.Instance.Receiver("false");
WINRTInterfaceHandler.Instance.Receiver("true"); Store.CurrentApp.ReportProductFulfillment(mproductLicense.ProductId); } else if (!mproductLicense.IsConsumable && mproductLicense.IsActive) { WINRTInterfaceHandler.Instance.Receiver("true"); } else { } } } catch{ }
var licence = Store.CurrentApp.LicenseInformation.ProductLicenses[productId];
}//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); if (licence.IsActive) {
if (bannerad != null && DrawingSurfaceBackground.Children.Contains(bannerad))
//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 { {
DrawingSurfaceBackground.Children.Add(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; AdRequest adrequest = new AdRequest();
if (bannerad != null && DrawingSurfaceBackground.Children.Contains(bannerad))
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 { { bannerad.Visibility = Visibility.Collapsed; } } break; }
private void OnAdReceived(object sender, AdEventArgs e) { interstitialAd.ShowAd();
}
Thanks

Native call backs and Monetization of Cocos 2d-x Games for windows phone 8 platform (Ads and IAP integration)

 Hi Folks!  In the Previous posts I mentioned the basic setup for windows phone 8 Cocos 2d-x game and issues along with solutions.Now lets see how to write call back functions in a cocos 2d-x games to communicate with the c# code (generated code) and vice versa.
1) Basic Call Backs Handling:
Any c++ run time component can communicate with your native code. In this sample I am following the standard ref class and event handlers to handle the communication process.
a) First we will need to add these following classes into your project, in visual studio under (If your project name is some thing like HelloCpp) HelloCppComponent section.
- First Right click on the HelloCppComponent
- Goto Add and select Class
- Select Visual studio C++ class
- Name it as ICallBackHandler
- You will now see an .h and a .cpp file created
- Fill these files with the following content
(ICallBackHandler.h,ICallBackHandler.cpp)
I) ICallBackHandler.h
namespace PhoneDirect3DXamlAppComponent //thi
{
using namespace Platform;
namespace WFM = Windows::Foundation::Metadata;
public enum class eEXTERNAL_REQ_TYPE
{
Initialize = 0, // initializing internet check and other things
InAppConsumable,       //1
InAppNonConsumable,    //2
Show_Banner_Top_Ads,   //3
Show_Banner_Bottom_Ads,   //4
Show_FullScreen_Ads,   //5
Hide_Banner_Ads,    //6
Hide_FullScreen_Ads   //7
} ;

[WFM::WebHostHiddenAttribute]
public interface class ICallBackHandler //Interface class
{
public:
virtual void  OnSendRequest(PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE eReqType, Platform::String ^strData); };
public delegate void CallBackHandler(PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE RequestType, Platform::String^ strData, Platform::String^ strResult);
public ref class ExternalInterfaceHandler sealed //EventArgs
{
public:
event CallBackHandler^ OnCallBack;
public:
property Platform::String^ mPrevRequestedData;
property PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE mPrevRequestType;
//Cx event Handling
public:
event CallBackHandler^ mInternalOnCallBack;
event CallBackHandler^ mEventRegistrationTokenHandler
{
Windows::Foundation::EventRegistrationToken add(CallBackHandler^ handler)
{
return mInternalOnCallBack += handler;
}
void remove(Windows::Foundation::EventRegistrationToken token)
{
mInternalOnCallBack -= token;
}

void raise(PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE RequestType,     Platform::String^ strData, Platform::String^ strResult)
{
mInternalOnCallBack(RequestType, strData, strResult);
}
}

//Singleton Instance
public:
static property ExternalInterfaceHandler^ Instance
{
ExternalInterfaceHandler^ get()
{
   static ExternalInterfaceHandler^ instance;
   if (instance == nullptr)
       instance = ref new ExternalInterfaceHandler();
 return instance;
 }

}
public:
virtual ~ExternalInterfaceHandler() { }
private:
ExternalInterfaceHandler() { }
public:
static void SetCallback(ICallBackHandler ^Callback);

void Reciever(PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE eRequestType, Platform::String ^mRequestedData, Platform::String^ mRequestedResult);

void SendRequest(PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE eRequestType, Platform::String ^mRequestedData, CallBackHandler^ OnRecieverCallBack);

};

}

Lets add the definitions for the class
  1.  II) ICallBackHandler.cpp
#include<ICallBackHandler.h>

#include <stdlib.h>

#include <assert.h>

#include <time.h>

using namespace PhoneDirect3DXamlAppComponent;

namespace PhoneDirect3DXamlAppComponent

{

Windows::Foundation::EventRegistrationToken mEventRegtokenCookie;

static int _mfPrevTimeOfAdsDisplay = 0;

ICallBackHandler ^CSCallback = nullptr;

void ExternalInterfaceHandler::SetCallback(ICallBackHandler ^Callback)

{

CSCallback = Callback;

}

void ExternalInterfaceHandler::Reciever(

PhoneDirect3DXamlAppComponent:: eEXTERNAL_REQ_TYPE eRequestType, Platform::String ^mRequestedData,

Platform::String^ msResult)

{
switch (eRequestType)
{
case
PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::InAppConsumable:
case   PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::InAppNonConsumable:
{
OnCallBack(mPrevRequestType, mPrevRequestedData, msResult);
OnCallBack -= mEventRegtokenCookie;
}
break;
default:
break;
}
}

void ExternalInterfaceHandler::SendRequest(PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE eReqType, Platform::String ^strRequesdData, CallBackHandler^ OnRecieverCallBack)
{
if (OnRecieverCallBack != nullptr)
{
mPrevRequestedData = strRequesdData;
mPrevRequestType = eReqType;
mEventRegtokenCookie = OnCallBack += OnRecieverCallBack; 
//standard registration for Cx/C++
}
switch (eReqType)
{
case PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::Show_FullScreen_Ads:
{
try
{
//make sure some 30 secs Delay between two full screen ads
time_t timep=time(NULL);
struct tm * timeinfo;
time(&timep);
timeinfo = localtime(&timep);
int presentTime = timeinfo->tm_sec;
if (abs(presentTime - _mfPrevTimeOfAdsDisplay) >= 30)
{
_mfPrevTimeOfAdsDisplay = presentTime;
  if (CSCallback != nullptr)
       CSCallback->OnSendRequest(eReqType, strRequesdData);

}
}
catch (Platform::Exception ^e)
{
}
}
break;
case  PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::Show_Banner_Top_Ads:
case  PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::Show_Banner_Bottom_Ads:
case PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::Hide_Banner_Ads:
case PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::Initialize:
case PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::InAppConsumable:
case PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::InAppNonConsumable:
{
if (CSCallback != nullptr)
     CSCallback->OnSendRequest(eReqType, strRequesdData);

}

break;
default:
break;
}//Switch
}//SendRequest
}
Note: What this essentially does is that it defines a virtual class that can be derived in you own code for the communication purpose.
After Adding the above two files
- Include the ICallBackHandler.h file in the required cpp class where you will need to communicate with the c#code
- Add using namespace PhoneDirect3DXamlAppComponent
- Add using namespace Platform (This is so that the String^ works without errors)
- Define the function that you will be using as a call back in your code (use the following code as a template)
#include<ICallBackHandler.h>
using namespace PhoneDirect3DXamlAppComponent;
using namespace Platform;
// Declare a call back function as follows:
public:
void OnIAPCallBack(PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE          eReqType,Platform::String^ strRequestedData, Platform::String^ strPurchaseStatus);
// Use the call back function as follows for IAP calls

ExternalInterfaceHandler::Instance-> SendRequest(PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::InAppConsumable,

"1", ref new CallBackHandler([this](PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE eRequestType, Platform::String ^mRequestedData, Platform::String^ mRequestedResult){OnIAPCallBack(eRequestType, mRequestedData, mRequestedResult); }));

// use the call back function as follows for Advertising calls (show ads (banner, full screen), hide ads)

ExternalInterfaceHandler::Instance->SendRequest(PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::Show_Banner_Bottom_Ads, "", nullptr);

ExternalInterfaceHandler::Instance->SendRequest(PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::Show_Banner_Top_Ads, "", nullptr);

ExternalInterfaceHandler::Instance->SendRequest(PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::Show_FullScreen_Ads, "", nullptr);

ExternalInterfaceHandler::Instance->SendRequest(PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE::Hide_Banner_Ads, "", nullptr);

Definition for Call back Function:

void PlayMenu::OnIAPCallBack(PhoneDirect3DXamlAppComponent::eEXTERNAL_REQ_TYPE eReqType, Platform::String^ strRequestedData, Platform::String^ strPurchaseStatus)
{
if (strPurchaseStatus == "true")
{
//Here purchase completed successfully so give the coins or levels or reward the user with purchased goods
}
else
{
//Here purchase completed failed so don't give any goods
}
}
2) Now let’s build the project and next open the MainPage.xaml.cs file
I) Add this class in MainPage.xaml.cs:
public class WINRTBridgeInterface : ICallBackHandler
{
InterstitialAd interstitialAd;
AdView bannerad;
private const string Admob_Banner_Id = "ca-app-pub-6086640554461020/1726002193";
private const string Admob_Intenstial_Id = "ca-app-pub-6086640554461020/3202735395";
private string InAppIdstringId = "Sampleproductid";
private MainPage m_MainPage = null;
private Direct3DInterop m_d3dInterop = null;
public WINRTBridgeInterface()
{
ExternalInterfaceHandler.SetCallback(this);
}
public void Initialize(MainPage mainPage,Direct3DInterop d3dInterop)
{
m_MainPage = mainPage;
m_d3dInterop = d3dInterop;
}
private void OnAdReceived(object sender, AdEventArgs e)
{
interstitialAd.ShowAd();
}

public void OnSendRequest(eEXTERNAL_REQ_TYPE eReqType, String   strRequestedData)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
switch (eReqType)
{
case eEXTERNAL_REQ_TYPE.InAppConsumable:
case eEXTERNAL_REQ_TYPE.InAppNonConsumable:
{
Deployment.Current.Dispatcher.BeginInvoke(async () =>
{
strRequestedData = InAppIdstringId + strRequestedData;
string productId = strRequestedData;
if (eReqType == eEXTERNAL_REQ_TYPE.InAppConsumable)
{
try
{
var licence = Store.CurrentApp.LicenseInformation.ProductLicenses[productId];
if (licence.IsActive)
{
Store.CurrentApp.ReportProductFulfillment(productId);
}
else
{
await Store.CurrentApp.RequestProductPurchaseAsync(productId, false);
var mproductLicense = Store.CurrentApp.LicenseInformation.ProductLicenses[productId];
if (mproductLicense.IsConsumable && mproductLicense.IsActive)
{
ExternalInterfaceHandler.Instance.Reciever(eReqType, strRequestedData, "true");
Store.CurrentApp.ReportProductFulfillment(mproductLicense.ProductId);
}
else
{
ExternalInterfaceHandler.Instance.Reciever(eReqType, strRequestedData, "false");                                             }
}
}
catch
{
ExternalInterfaceHandler.Instance.Reciever(eReqType, strRequestedData, "false");
}
}//consumable goods
else if (eReqType == eEXTERNAL_REQ_TYPE.InAppNonConsumable)
{
try
{
if (Store.CurrentApp.LicenseInformation.ProductLicenses[productId].IsActive)
{
ExternalInterfaceHandler.Instance.Reciever(eReqType, strRequestedData, "true");                                        }
else
{
await Store.CurrentApp.RequestProductPurchaseAsync(productId, false);
var licence = Store.CurrentApp.LicenseInformation.ProductLicenses[productId];
if (licence.IsActive)
{
ExternalInterfaceHandler.Instance.Reciever(eReqType, strRequestedData, "true");
}
else
{
ExternalInterfaceHandler.Instance.Reciever(eReqType, strRequestedData, "false");                                               }
}
}
catch
{
ExternalInterfaceHandler.Instance.Reciever(eReqType, strRequestedData, "false");                                    
}
}//Durable goods
});
}
break;
case eEXTERNAL_REQ_TYPE.Show_Banner_Top_Ads:
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (DeviceNetworkInformation.IsNetworkAvailable) //check if net                           is available or not
{
if (bannerad != null && m_MainPage.LayoutRoot.Children.Contains(bannerad))
{
bannerad.VerticalAlignment = VerticalAlignment.Top;
bannerad.Visibility = Visibility.Visible;
}
else
{
bannerad = new AdView();
bannerad.Format = AdFormats.Banner;
bannerad.VerticalAlignment = VerticalAlignment.Top;
bannerad.AdUnitID = Admob_Banner_Id;
m_MainPage.LayoutRoot.Children.Add(bannerad);
AdRequest adrequest = new AdRequest();
bannerad.LoadAd(adrequest);
}
}
});
}
catch
{
}
}
break;
case eEXTERNAL_REQ_TYPE.Show_Banner_Bottom_Ads:
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (DeviceNetworkInformation.IsNetworkAvailable) //internet availablity
{
if (bannerad != null && m_MainPage.LayoutRoot.Children.Contains(bannerad))
{
bannerad.VerticalAlignment = VerticalAlignment.Bottom;
bannerad.Visibility = Visibility.Visible;
}
else
{
bannerad = new AdView();
bannerad.Format = AdFormats.Banner;
bannerad.VerticalAlignment = VerticalAlignment.Bottom;
bannerad.AdUnitID = Admob_Banner_Id;
m_MainPage.LayoutRoot.Children.Add(bannerad);
AdRequest adrequest = new AdRequest();
bannerad.LoadAd(adrequest);
}
}
});
}
catch
{
}
}
break;
case eEXTERNAL_REQ_TYPE.Show_FullScreen_Ads:
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (DeviceNetworkInformation.IsNetworkAvailable) //check if net is available or not
{
interstitialAd = new InterstitialAd(Admob_Intenstial_Id);
AdRequest adRequest = new AdRequest();
interstitialAd.ReceivedAd += OnAdReceived;
interstitialAd.LoadAd(adRequest);
}
});
}
catch
{
}
}
break;
case eEXTERNAL_REQ_TYPE.Hide_Banner_Ads:
case eEXTERNAL_REQ_TYPE.Hide_FullScreen_Ads:
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (bannerad != null && m_MainPage.LayoutRoot.Children.Contains(bannerad))
{
bannerad.Visibility = Visibility.Collapsed;
}
});
}
break;
}
});
}
}
  II) And again in the MainPage.xaml.cs file update the following function
private void DrawingSurface_Loaded(object sender, RoutedEventArgs e)
{
// add these lines, this is important coz all call backs initialized with these lines only
WINRTBridgeInterface WINRTBridgeObj = new WINRTBridgeInterface();
WINRTBridgeObj.Initialize(this, m_d3dInterop);
}
Congratulations you have successfully finished the setup and now your code can communicate between c++ to c# and vice versa. Cheers!!!!!!
Thanks!

Monday, 1 September 2014

Porting the Cocos 2d-x Games to windows phone 8 and Windows 8 platforms

In this article i will demonstrate how to port an existing Cocos2d-x game written in C++ to windows platforms with step by step instructions. I'll try to  cover all important aspects along with some tips.
Software requirements :
1)  Visual studio 2013
2)  Cocos 2d-x 2.3.2 frame work
 Process step by step :
1. Open the cocos 2d-x frame work and select the template folder (2.2.3 version on wards Google ad mob will work)
2. Open the template folder and  selcet the multi-platform-cpp folder and open it
3.  Select the proj.wp8-xaml and double click on it
4.  Open the HelloCpp.sln visual studio project.
5.   After opening the project add the classes and resources to the project as follows
  1.   Right click on the classes folder in HelloCppComponent and select the add then click followed by Existing Item  Navigate to classes and select the required classes and add them.
  2.   Copy the all resources in your game and right click on the Assets folder in HelloCpp
then select the show in explorer and paste the resources there.
Now the setup is finished and we have to handle the errors and other things.
6. Find any deprecated methods in your project  and replace them with new methods.
Example : Random instead of Rand function.
7. Check out the errors in out put or Error window and fix them one by one
Example: The methods which are used to create the GUI elements (Buttons, labels, Images, HUD) should be  declared such a way that should take atleast one arguement generally pass  CCObject *psender argument.
Audio support on Windows Phone :
1. Convert all the sound files into .wav format using the software like Audacity. and copy them to project resources folder.
2. Make sure .wav extension in code to play the audio. Find all as follows Ctrl+Shift+F,it will search in whole solution
then replace  .wav instead of.mp3.
3. As if you want to maintain the universal project use the the platform specific code
#if CC_TARGET_PLATFORM == CC_PLATFORM_WP8 ||  CC_TARGET_PLATFORM ==CC_PLATFORM_WINRT
{
audioEngine->preloadEffect("sampleEffect.wav");
audioEngine->playBackgroundMusic("sampleBGSound.wav",true);
}
#else
{
audioEngine->preloadEffect("sampleEffect.mp3");
audioEngine->playBackgroundMusic("sampleBGSound.mp3",true);
}
#endif
Font support on Windows Phone :
For Windows Phone use the supported fonts rather than using the differrent one. use the platform specific code for
universal projects. check here for supported fonts

#if CC_TARGET_PLATFORM == CC_PLATFORM_WP8 || CC_TARGET_PLATFORM ==CC_PLATFORM_WINRT
this->Gamelabel = CCLabelTTF::create("Score : ", "Arial", 20);
#else
this->Gamelabel = CCLabelTTF::create("Score : ", "Helvetica", 20);
#endif
Note: CC_PLATFORM_WP8 for Windows phone 8 and CC_PLATFORM_WINRT for windows 8 games.
5) Device back button: [mandotory for app certification]
1. To add the back button just have a virtual method in the base class and Override in the sub classes.
In AppDelegate class we have to set the layer and depends on the layer name call the back button if it's null then call the application exit
void Layer::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event) //use the function like this:
void MyLayer::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event)
{
if (keyCode == EventKeyboard::KeyCode::KEY_ESCAPE)
{
CCLOG("You pressed back button");
Director::getInstance()->end();
exit(0);
}
}
6) Background music continuous looping problem even App went to background State:
I)To fix this problem first of all  Open the AppDelegate.cpp
void AppDelegate::applicationDidEnterBackground()
{
CCDirector::sharedDirector()->pause();
CCDirector::sharedDirector()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
CCDirector::sharedDirector()->resume();
CCDirector::sharedDirector()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
CocosDenshion::SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}
   II) Open the cocos2dRenderer.Cpp
In CreatGLResources method add the following line
mApp->applicationWillEnterForeground(); //Add this line to call the application activation state
void Cocos2dRenderer::CreateGLResources()
{
mApp->applicationWillEnterForeground(); //Add this line
}
In Disconnect method add the following line
mApp->applicationDidEnterBackground(); //Add this line to call the application background state
// purge Cocos2d-x gl GL resourses since the DirectX/Angle Context has been lost
void Cocos2dRenderer::Disconnect()
{
mApp->applicationDidEnterBackground();
}
7) Device Acceleration (tilt):
Add the following Files AcceleratorDelegate.h, AcceleratorDelegate.cpp
1) AcceleratorDelegate.h
#pragma once
class GameScene;
ref class AcceleratorDelegate sealed
{
public:
static property AcceleratorDelegate^ AcceleratorInstance
{
AcceleratorDelegate^ get()
{
static AcceleratorDelegate^ instance;
if (instance == nullptr)
instance = ref new AcceleratorDelegate();
return instance;
}
}
public:
virtual ~AcceleratorDelegate(void) { }
private:
AcceleratorDelegate(void);
// ~AcceleratorDelegate(void);
public:
void ReadingChanged(Windows::Devices::Sensors::Accelerometer^ sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^ e);
private:
Windows::Devices::Sensors::Accelerometer^ m_accelerometer;
Windows::Foundation::EventRegistrationToken m_readingToken;
uint32 m_desiredReportInterval;
};
2)AcceleratorDelegate.cpp
#include "AcceleratorDelegate.h"
using namespace Windows::Devices::Sensors;
using namespace Windows::Foundation;
using namespace Platform;
AcceleratorDelegate::AcceleratorDelegate(void) //default constructor
{
m_accelerometer = Accelerometer::GetDefault();
if (m_accelerometer != nullptr)
{
// This value will be used later to activate the sensor.
uint32 minReportInterval = m_accelerometer->MinimumReportInterval;
m_desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
m_readingToken = m_accelerometer->ReadingChanged::add(ref new         TypedEventHandler<Accelerometer^, AccelerometerReadingChangedEventArgs^>(this, &AcceleratorDelegate::ReadingChanged));
}
//end if m_accelerometer
}
void AcceleratorDelegate::ReadingChanged(Windows::Devices::Sensors::Accelerometer^ sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^ e)
{
AccelerometerReading^ reading = e->Reading;
//X-reading->AccelerationX -->send as y value
//Y-reading->AccelerationY --> send as -x value
//Z-reading->AccelerationZ
}

Unity 3D Optimization and best Practices

Unity 3D Optimization and best Practices
1) Textures:
  It depend on so many factors first of all try to use the textures to a power of two (256x256, 512x512 and 1024x1024 etc.)  And depends on the platform we have to use the texture compression
 IOS:   Preferable is PVRTC
 Android/ BlackBerry:   PVRTC compression is best
 Windows Phone/Pc:   DX1 is the preferable for environment texture (without alpha), DX5 is the preferable for GUI texture (with alpha)
 Work with a high-resolution source file outside your unity project (such as a PSD or Gimp file). You can always downsize from source but not the other way round. 
Use the texture resolution   output you require in your scene (save a copy, for example a 256x256 optimized PNG or a TGA file). You can make a judgment based on where the texture will be seen and where it is mapped.
Store your output texture files together in your Unity project (for example: \Assets\textures). Make sure your 3D working file is referring to the same textures for consistency when you save/export.
 Make use of the available space in your texture, but be aware of different materials requiring different parts of the same texture. You can end up using/loading that texture multiple times. For alpha (cutout) and elements that may require different shaders, separate the textures. For example, the single texture below (left) has been replaced by three smaller textures below (right) Make use of tiling textures (which seamlessly repeat) then you can use better resolution repeating over space Unity takes care of compression for the output platform, so unless your source is already a JPG of the correct resolution it’s better to use a loss less format for your textures. When creating a texture page from photographs, reduce the page to individual modular sections that can repeat.  For example, you don’t need twelve of the same windows using up texture space. That way you can have more pixel detail for that one window.

2) Sound files:
Use the compress the large files like Background music use uncompressed for small music like  button click sound and effects if size is greater than 100kb try to make it less than 100 by setting  the compression rate   and load type as stream from disc or compressed in memory (64 bit compression is preferable)

3) Model Optimization (Mesh data):

Set your system and project units for your software to work consistently with Unity e.g. Metric.  Do not scale the object try to use the uniform scaling as if you want to scale the object scale the FBX by changing the scale factor.  Working to scale can be important for both lighting and physics simulation.  Be aware that, for example, the Max system unit default is inches and Maya is centimeters.  Unity has different scaling for FBX and 3D application files on import check the FBX import scale setting in Inspector.  Animation frame rate defaults can be different in packages, is a good idea to set consistently across your pipeline, for example 30fps.

4) Mesh Optimization :
static batching is only works if your model consists of less than 300 trice  so make sure the trice count is less much as possible  Build with an efficient topology. Use polygons only where you need them.  Optimize your geometry if it has too many polygons. Many character models need to be intelligently optimized or even rebuilt by an artist especially if sourced/built from: 1) 3D capture data 2)  Poser 3) Z brush
 Other high density Nurbs/Patch models designed for render Where you can afford them, evenly spaced polygons in buildings, landscape and architecture will help spread lighting and avoid awkward kinks. Avoid really long thin triangles.

5) Shaders :
try to use the mobile version of shaders as it will gives the best performance as if you want to go with your custom  shaders that's very good alternative for you.  Avoid the pixel light shaders use the custom sphere or plane and avoid the standard sky box as it will cost 8 Draw calls.

6) Scripting Optimization:
  Void OnBecameVisible () {
      enabled = true;
         }
        void OnBecameInvisible () {
       enabled = false;
      }
1) Use OnBecameVisible and OnBecameInvisible methods automatically 
These two functions will make sure the code optimization techniques as if camera rendering the object then only script will be in running state else would be in disable state it would be use for effects and coins rotation scripts. We can reduce the over head

 2) Try to avoid the finding the game objects at run time (just load once in Start or Awake)

 3) Try to use the generic GUI like NGUI try to run less updates and On GUI methods.

 4) For Object pooling you can get here.
  http://thepigstudio.com/common-patterns-in-unity3d-singleton-and-object-pooling/
references :
1) http://wiki.unity3d.com/index.php?title=General_Performance_Tips
2) http://docs.unity3d.com/Manual/ReducingFilesize.html
3) http://docs.unity3d.com/Manual/HOWTO-ArtAssetBestPracticeGuide.html
4)http://docs.unity3d.com/Documentation/Manual/OptimizingGraphicsPerformance.html
5)http://docs.unity3d.com/Documentation/Manual/ReducingFilesize.html
6)http://unity3d.com/Documentation/Manual/Character-Animation.html
7)http://www.digitaltutors.com/tutorial/1467-Game-Optimization-Techniques-in-Unity