miércoles, 24 de febrero de 2016

Como instalar Tappx y Admob en una misma App | How to install Tappx and Admob in the same app

Español | English


Como mencioné en mi entrada anterior, esta entrada será sobre los pasos a seguir para implementar Admob y Tappx. Repaso para lo que no saben, Admob es una red publicitaria que nos permite poner publicidad en nuestros juegos mientras que Tappx en vez de publicidad muestra juegos de otros desarrolladores y a cambio, ellos muestran nuestro juego. Aviso: Este tutorial será para instalar publicidades de pantalla completa (Interstitial) y será dirigido para Android.

Por qué hacer este proceso? : Si bien Admob muestra publicidades y puede hacernos ganar dinero, Tappx se encargará de que nuestro juego sea más conocido, ya que estaríamos promocionándolo. Lo más conveniente para mi es intercalar entre mostrar 1 publicidad de Admob y 1 de Tappx y repetir esa secuencia. 

Para lo siguiente empecemos por implementar Admob:


  1. Para eso debemos descargarnos el plugin de Admob para Unity desde su página en Github: https://github.com/googleads/googleads-mobile-unity/releases tienen que bajarse la última versión que este disponible (la versión debe ser desde la 3.0 en adelante).
  2. Importamos el paquete en Unity: Assets/Import/Custom Package y seleccionamos el plugin que nos acabamos de descargar.
  3. Una ventana se nos abrirá indicando que archivos queremos importar, para esto recomiendo que si nuestro juego es solo para Android no para IOS, destildar las casillas que digan "IOS" ya que no las vamos a necesitar.
  4. Abrimos el Manifest que esta dentro de la carpeta Plugins/Android/GoogleMobileAdsPlugin y quitar un par de líneas de código: Desde la línea de código 22 que empieza con " <!-- Google Mobile Ads Activity -->" hasta la línea 28 que termina con "android:theme="@style/Theme.IAPTheme"/>" . Con esto nos aseguramos de borrar la actividad que complica la compatibilidad con Google Play Services y la actividad de "nAppPurchase Activity" que es para juegos con micropagos. (En caso de que el juego tenga micropagos deshacer este último paso y borrar solamente la actividad de Google Mobile Ads Activity).
Y listo, ya tenemos instalado Admob, la parte de código la haremos al final todo junto pero lo que falta en el caso de que queramos solamente instalar Admob sería, por código, insertar nuestra ID the Admob y especificar cuando hacer el AdRequest, AdLoad y AdShow.

Implementación de Tappx (más fácil):

  1. Crear una cuenta en www.tappx.com
  2. Añadir nuestra app haciendo click en "Añadir App" y completando el formulario
  3. Descargamos su SDK desde su página oficial http://www.tappx.com/es/manual/?os=uni#0_gettingStarted
  4. De nuevo ir a Assets/Import/Custom Package y ahora con cuidado, des-seleccionamos el AndroidManifest que aparece cerca del principio ya que nuestro proyecto lo tiene.

  5. En caso de ya haber instalado Google Play Services en nuestro proyecto, des-seleccionamos también esta carpeta y de nuevo, si no utilizamos IOS podemos des-tildarla también.
  6. Una vez importado vamos a TappxManagerUnity.prefab e introducimos nuestra ID de Android o IOS o ambas si utilizaremos los 2 servicios y tambien tildamos si solo utilizaremos banners o interstitials.




Abajo explico donde podemos encontrar nuestra ID de Tappx. Por último vamos a el Android Manifest que está dentro de la carpeta /Plugins/Android/GoogleMobileAdsPlugin y al final, antes de </application> copiamos lo que va a servir para el "Track" de la aplicación:


<receiver android:name="com.tappx.unity.InstallReferrerReceiver" android:exported= "true" > 
<intent-filter> 
<action android:name="com.android.vending.INSTALL_REFERRER" /> 
</intent-filter> 
 <meta-data android:name="forward.GoogleAnalytics" android:value="com.google.android.apps.analytics.AnalyticsReceiver" />
 </receiver>

Ahora compilamos para ver que no haya errores. Hacemos esto yendo a File/Build Settings/Build, primero nos fijamos que la plataforma Android este seleccionada, en caso de ser otra, seleecionamos Androidy apretamos en "Switch Platform". Luego nos preguntará a donde queremos guardar el archivo (APK), elegimos y le damos Build. Antes de compilar vamos a "Player Settings" y en "Other Settings" vamos a "Identification" y ahí a "Bundle Identifier" que el default suele ser "com.Comany.ProductName" y cambiamos "Company" y "ProductName" por lo que queramos, yo puse para esta prueba "com.companiaprueba.prueba" y ya eso funciona para probar si compila.

Ahora la parte de código. Necesitamos un Script "General" que funcione para el comportamiento "General" del juego en caso de no tenerlo, podemos crearlo o podemos poner el código en el lugar que más le parezca conveniente.

Debemos entender que las publicidades funcionan con tres pasos:

  1. AdRequest: La publicidad le "pide" a su red que le envíe una publicidad para mostrar
  2. AdLoad: Esta parte se encarga de cargar la publicidad pedida para que este lista para mostrar
  3. AdShow: Mostrar la publicidad, este evento solo se cierra cuando el usuario cierra la publicidad.
Para ello un script sencillo podría ser:


using System;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using GoogleMobileAds;
using GoogleMobileAds.Api;
using GooglePlayGames;

using UnityEngine.SocialPlatforms;

//variables a utilizar más adelante
 private InterstitialAd interstitial;
 AndroidJavaObject interstitialControl;
int ad = 1;


void Start() {  //Es conveniente poner en Start los request para que se inicien cuando carga el juego                              aunque puede hacer que el juego se tilde al iniciar



 RequestInterstitial(); //admob request

        interstitialControl = new AndroidJavaObject("com.tappx.unity.interstitialTappx", "TappxID", "TappxManagerUnity"); //tappx request
}

void Perder(){ //esta parte será para cuando nuestro jugador pierda trate de lo que se trate el jeugo

 if (ad % 2 != 0)  //más abajo explicaré esta parte del código
        {
            ShowInterstitial(); //admob interstitial
            ad++;
        }
        else
        {
            //interstitial.Show();
            interstitialControl.Call("showInterstitial");     //tappx interstitial
            ad++;

}



Poner los Request en la función Start funciona para los juegos que al perder se reinician, en caso de usar otro método habría que ubicarlos en otra función. Ahora toda la parte siguiente es la parte que hay que agregar de parte de Admob y Tappx, son funciones que ellos mismos proveen: 


 private void RequestInterstitial() //request inter
    {

#if UNITY_EDITOR
        string adUnitId = "unused";
#elif UNITY_ANDROID
            string adUnitId= "Insert AdmobID";
#else
        string adUnitId = "unexpected_platform";
#endif

        // Create an interstitial.
        interstitial = new InterstitialAd(adUnitId);

        // Load an interstitial ad.
        interstitial.LoadAd(createAdRequest());
    }
    

    // Returns an ad request with custom ad targeting.
    private AdRequest createAdRequest()
    {
        return new AdRequest.Builder()
                .AddTestDevice(AdRequest.TestDeviceSimulator)
                .AddTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4")
                .AddKeyword("game")
                .SetGender(Gender.Male)
                .SetBirthday(new DateTime(1990, 1, 1))
                .TagForChildDirectedTreatment(false)
                .AddExtra("color_bg", "9B30FF")
                .Build();
    }


    private void ShowInterstitial()
    {
        if (interstitial.IsLoaded())
        {
            interstitial.Show();
        }
        else
        {
            print("Interstitial is not ready yet.");
        }
    }

    // Tappx
    
    public void InterstitialLoaded()                        //check ad loaded
    {
        UnityEngine.Debug.Log("Interstitial Load");
    }

    public void InterstitialFailedToLoad(string error)
    {
        UnityEngine.Debug.Log("Interstitial Error " + error);
    }




Borre un par de datos por lo que copiar y pegar no funcionará, deben agregar en sus IDs de Admob y Tappx en las partes correspondientes y en AddTestDevice puse lo que viene por default en la guía de Admob.

La ID de Tappx la podemos ver haciendo click en nuestra lista de Apps de nuestra cuenta

Luego de todas esas cosas volvemos al perder: Cuando uno pierde sea cual sea el motivo del juego mostramos una publicidad de Admob y cuando pierda de nuevo, una publicidad de Tappx, puede ser al revés si se quiere.

Para esto estuve mucho tiempo pensando y se me ocurrió que lo mejor sería hacer una escala de par-impar. Tenemos nuestra variable "ad" con valor inicial en 1, al perder la función se pregunta si es par (si "ad" dividido 2 da como resto 0), si es el caso, mostrar una publicidad de Admob y sumarle 1 a "ad", para la próxima vez, "ad" será 2, por lo que al perder, se preguntará de nuevo si es par o impar, como 2 es par esta vez se mostrará una publicidad de Tappx y se sumará de nuevo 1 a "ad" y así sucesivamente.

Aparte de la personalización que cada uno debería agregar para ajustar esto a su juego, esto es a grandes rasgos el mejor método que encontré para agregar publicidad y promocionar el juego al mismo tiempo. Cualquier consulta puede dejarla en los comentarios.

-L


-------------------------------------------------------------------------------
English



I as mentioned on my last entry, this entry will be about the steps to implement Admos and Tappx. A note for whose who doesn't know, Admob is a plublicity net which enable us to put ads on our games while Tappx instead of ads it shows game of other devs, in return, they show ads of our game.  Note: This tutorial will be to install full screen ads (Interstitial) and will be adressed to Android.

Why to do this process? : Although Admob shows ads and we can earn money, Tappx will take care of getting our game some downloads, so we would be promoting it. The most convinient is to switch between 1 Admod ad and 1 Tappx ad and repeat this sequence.



Which the following steps we will implement Admob:
  1. We need to download the plugin of Admob for Unity, from their Github page https://github.com/googleads/googleads-mobile-unity/releases and download the lastest version available ( the version needs to be from 3.0 onwards)
  2. We Import the package in Unity by going to Assets/Import/Custom Package and we select the downloaded plugin
  3. A window will opwn indicating the files we want to import, for this I recommend that if our game is only for Android and not for IOS, uncheck all the IOS folders as we won't need them
  4. We open the Manifest which is inside the folder  Plugins/Android/GoogleMobileAdsPlugin and we are gonna eliminate a few lines of code: From line 22 which starts with " <!-- Google Mobile Ads Activity -->" to line 28 which ends with "android:theme="@style/Theme.IAPTheme"/>" . With this we make sure to eliminate the activity that causes troubles with Google Play Services and the "InAppPurchase Activity" which is for games that have In App Purchase (In the case that our game does includes in app purchase, we undo this last step and only erase the "Google Mobile Ads Activity" Activity).
And done, we already have Admob installed, the part of coding will be done in the end all together but what it needs to be done in case we only wanted to install Admob wil be, by code, instert our AdmobID and specify when we want to do the AdRequest, AdLoad y AdShow.

Tappx Implementation (easier):


  1. Create an account on www.tappx.com
  2. Add your app by clicking on "Add App" and complete the form
  3. Download the SDK form their official page http://www.tappx.com/es/manual/?os=uni#0_gettingStarted
  4. Go again to Assets/Import/Custom Package and now with care, we uncheck the AndroidManifest which is near the top as our project already has one.

  5. In case that your project already has installed the Google Play Services, we uncheck the folder and if we won't use IOS, we uncheck them too.
  6. Once imported we go to the TappxManagerUnity.prefab and introduce our ID of Android or IOS or both if we are gong to use both services and check if we are going to use banners or interstitials.





Below I explain where you can find your Tappx ID. Finally, we go to the Android Manifest which is inside the folder /Plugins/Android/GoogleMobileAdsPlugin and before the </application>, we copy what Tappx will use for tracking the app:


<receiver android:name="com.tappx.unity.InstallReferrerReceiver" android:exported= "true" > 
<intent-filter> 
<action android:name="com.android.vending.INSTALL_REFERRER" /> 
</intent-filter> 
 <meta-data android:name="forward.GoogleAnalytics" android:value="com.google.android.apps.analytics.AnalyticsReceiver" />
 </receiver>

Now we compile in order to see there are no errors. We do this by going to File/Build , first we check our platform to Android, if it wasn't checked before we select Android and we press on "Switch Platforms". Then it will ask us where we want to save the file (APK) we select and press Build. But before we compile we go to "Player Settings" and "Other Settings", then we go  to "Identification" and ther to "Bundle Identifier", the default is "com.Comany.ProductName" where we will change the "Company" and "ProductName" for whatever we like, I chosed for this test "com.testcompany.test" and with that you are ready to see if it compiles.

Now the code part. We need a  "General" Script which works for the general behaviour of the game, in case of not having one, we can create it or put this code where you thinks it suits your game.

But first we need to understand how ads works in three simple steps

  1. AdRequest: The ad "asks" to its network for an ad to show
  2. AdLoad: This part handles the request and prepares the ad to be shown
  3. AdShow: Show the ad, this event closes when the user closes the ad

A simple Script could be:

using System;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using GoogleMobileAds;
using GoogleMobileAds.Api;
using GooglePlayGames;

using UnityEngine.SocialPlatforms;


//variables that will be use forward

private InterstitialAd interstitial;
 AndroidJavaObject interstitialControl;
int ad = 1;


void Start() {  //Its convinient to put the request on Start so when the game starts the ads are loaded                               although it might make the game to freeze a little bit




 RequestInterstitial(); //admob request

        interstitialControl = new AndroidJavaObject("com.tappx.unity.interstitialTappx", "TappxID", "TappxManagerUnity"); //tappx request
}

void Lose(){ //This part will be for where the player loses

 if (ad % 2 != 0)  //Below I'll explain this part of the code
        {
            ShowInterstitial(); //admob interstitial
            ad++;
        }
        else
        {
            //interstitial.Show();
            interstitialControl.Call("showInterstitial");     //tappx interstitial
            ad++;
}

Putting the Requests on the Start function works for those game that restart after the player loses, in the case of using another method this should be reallocated  to another function. Now the whole next part is what you need to add by Admob and Tappx, its code they provide:

 private void RequestInterstitial() //request inter
    {

#if UNITY_EDITOR
        string adUnitId = "unused";
#elif UNITY_ANDROID
            string adUnitId= "Insert AdmobID";
#else
        string adUnitId = "unexpected_platform";
#endif

        // Create an interstitial.
        interstitial = new InterstitialAd(adUnitId);

        // Load an interstitial ad.
        interstitial.LoadAd(createAdRequest());
    }
    

    // Returns an ad request with custom ad targeting.
    private AdRequest createAdRequest()
    {
        return new AdRequest.Builder()
                .AddTestDevice(AdRequest.TestDeviceSimulator)
                .AddTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4")
                .AddKeyword("game")
                .SetGender(Gender.Male)
                .SetBirthday(new DateTime(1990, 1, 1))
                .TagForChildDirectedTreatment(false)
                .AddExtra("color_bg", "9B30FF")
                .Build();
    }


    private void ShowInterstitial()
    {
        if (interstitial.IsLoaded())
        {
            interstitial.Show();
        }
        else
        {
            print("Interstitial is not ready yet.");
        }
    }

    // Tappx
    
    public void InterstitialLoaded()                        //check ad loaded
    {
        UnityEngine.Debug.Log("Interstitial Load");
    }

    public void InterstitialFailedToLoad(string error)
    {
        UnityEngine.Debug.Log("Interstitial Error " + error);
    }


I deleted some data so copying and pasting won't work, you should add your Admob and Tappx Id on the corresponding parts of the code and on "AddTestDevice" I used the default value that Admob's guide uses.

You can see your Tappx ID by clicking on your App on the app's list of your account

Now we come back to losing: When one loses by whatever the reason to be, we show an Admob ad, when we lose again, we show a Tappx ad, it can be in the other way if you want.

For this I've been thinking a lot and I think that the best way of doing it is by cheking if a number is odd or even. For this we use the variable "ad" with an initial value of 1, when losing the function ask if "ad" is even (if the rest of dividing "ad" by 2 is 0), in that case, show and Admob ad and add 1 to "ad", for the next time, "ad" will be 2, so when losing, the function will ask again and as 2 is even it will show a Tappx ad and add 1 to "ad" and so on.

Besides the personalization that one sould add to adjust this code to its game, this is roughly the best way I found to show ads and promoting the game at the same time. Any questions will be accepted on the comments.

-L

No hay comentarios.:

Publicar un comentario