How to Create Unity Android Plugins?

Disclaimer: This is based on FastEgg’s Tutorial http://fastegggames.com/blog/2013/3/30/tutorial-admob

Sometimes we need to create Plugins to easily use external frameworks such as Ad Networks in Unity.

Android

1. Create new Android Application Project

* Application Name, Project Name should refer to the specific plugin (admob for a plugin for AdMob)

2. Add Additional Libraries

  • right click on Project and select “Properties”
  • navigate to “Java Build Path”
  • select “Libraries” tab
  • click on “Add External JARs”
  • add Unity’s “classes.jar” (located at <UnityInstallPath>\Editor\Data\PlaybackEngines\AndroidPlayer\bin\classes.jar)
  • add other JARs that are required by the plugin (such as AdMob’s jar)

Unity’s classes.jar

  • it is found in the installation folder
  • C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer\bin on Windows
  • /Applications/Unity/PlaybackEngines/AndroidPlayer/bin on Mac

  • select “Order and Export”
  • tick all external JARs to make sure that they will be exported together with the new JAR file

3. Code the Plugin

  • create new class with the same name as the project (such as AdMob.java)
  • make sure to give it the package name of your plugins package
  • create a Constructor
  • can refer to activity using UnityPlayer.currentActivity
package com.example.AdMob
public class AdMob
{ private Activity activity; //Store the android main activity

  //Constructor
  public AdMob()
  { activity =UnityPlayer.currentActivity;
  }
}

4. Export Plugin

  • right click on project and select “Export”
  • in the Export Window, select “Java/JAR file”
  • in Jar Export Window, make sure current project is ticked
  • set export location to our Unity Project’s “Assets\Plugins\Android folder”
  • name plugin (such as AdMob.jar)
  • the wizard will pack the jar file, making it available for Unity

* sometimes plugins require additional JARs to be included our Unity Project’s “Assets\Plugins\Android folder” (such as the AdMob SDK)

5. Call Plugin From Unity

  • create a new MonoBehaviour script in Unity, and name it closely to your plugin (such as AdMobController)
#pragma strict
public class AdMobController extends MonoBehaviour
{ function Awake()
  {
  }
}
  • to activate our new plugin, we need to create a new AndroidJavaObject, and by using our package name, we can have it cast to the type we created in our JAR file:
#pragma strict
public class AdMobController extends MonoBehaviour
{ private static var jo:AndroidJavaObject;
  function Awake()
  { 
   #if UNITY_ANDROID
   jo =newAndroidJavaObject("com.example.admob.AdMob");
   #endif
  }
}

6. Modifying the Manifest

  • Unity will usually create it’s own AndroidManifest.xml file when packaging your project, but also allows for you to override the one it creates with one you define inside of the Assets/Plugins/Android folder
  • you can either create one from scratch, or copy over the default one that Unity has created for your project
  • to get the default, make a build in Unity, and let it complete and save. Then look in your projects temp/stagingarea folder. There should be a AndroidManifest.xml file generated for you. Copy that to your projects Assets/Plugins/Android folder, and edit it using MonoDevelop
  • modify the Manifest file to include things required by your plugin (such as requires Internet): <uses-permission android:name=”android.permission.INTERNET” />
  • save changes

EDIT:

If you set your Android Application as Library, it’s Android Manifest will automatically be merged with any existing ones in your Unity project.

To set your project as Library, go to the project’s Properties > Android and tick Is Library, and click Apply.

It will add a project.properties file to your project, make sure to include that in your jar file.

Screen Shot 2015-01-09 at 4.57.34 PM

7. Testing

  • some Android related things (such as Ads) doesn’t show up in the Unity Editor, so you’d need to build and run on an Android device to test
  • you can use adb logcat in Terminal to debug while running on Android device
  • Ctrl+C stops logcat

That’s it!

Code Bit: How to use JNI in Cocos2dx Android?

Thank you, Bojun for helping me understand all this 🙂

You can first read up the Cocos2dx documentation on this: http://www.cocos2d-x.org/projects/cocos2d-x/wiki/How_to_use_jni

Basically JNI is this thing that allows you to call Java code from C++ and vice versa.

I’m gonna post a very round about code that I think shows how to do it both ways.

First off, in Java (my class name is sample.java), I have two additional methods:

public static native void printSomething();

public static void printSomethingFromJava()
{    printSomething();
}

The printSomething method corresponds to a method in my C++, while printSomethingFromJava is a method that is called from my C++.

So far so good?

And then in C++ (HelloWorld.cpp), I have the method that corresponds to the printSomething method in Java:

void Java_com_purple_sample_sample_printSomething(JNIEnv *env, jobject obj)
{    CCNotificationCenter::sharedNotificationCenter()->postNotification(“printSomethingInCPP”, NULL);
}

Basically, when you call printSomething in sample.java, this method is called.

So there, we can call a method in C++ from Java.

Notice the CCNotification (thank you so much, Bojun for teaching me this). Since I can’t call anything in HelloWorld, because it’s not part of the scene, I need to use CCNotification to call any methods from Hello World.

In order for a CCNotification to be called you need to add an observer first, so somewhere in HelloWorld’s init method:

CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(HelloWorld::printSomethingInCPP), “printSomething”, NULL);

printSomethingCPP is a method in HelloWorld that essentially adds a CCLabel to our scene:

void HelloWorld::printSomethingInCPP()
{    CCLabelTTF* pLabel = CCLabelTTF::create(“Hello World”, “Thonburi”, 34);

    // ask director the window size
    CCSize size = CCDirector::sharedDirector()->getWinSize();

    // position the label on the center of the screen
    pLabel->setPosition( ccp(size.width / 2, size.height/2) );

    // add the label as a child to this layer
    this->addChild(pLabel);
}

Still following?

So now, we can call a method in C++ from Java, and we use CCNotification to call another method that’s in the HelloWorld scene.

Next up! Calling a Java method from C++.

Remember the printSomethingFromJava method? That is a method that we will call from our C++.

So in C++, I created a method named printSomethingFromJava, and it contains some of these:

void HelloWorld::printSomethingFromJava()
{    JniMethodInfo t;
    if(JniHelper::getStaticMethodInfo(t, “com/purple/sample/sample”, “printSomethingFromJava”, “()V”))
    {    t.env->CallStaticVoidMethod(t.classID, t.methodID);
        // delete reference
        t.env->DeleteLocalRef(t.classID);
    }
}

Now, this code is what calls the printSomethingFromJava method in Java.

I call the printSomethingFromJava method in HelloWorld.cpp in its init method, somewhere after the CCNotificaton Add Observer.

This blog has a list of methods, return calls etc. for Android JNI: http://blog.csdn.net/lizhiguo0532/article/details/7219357.

Okay, so it’s a little confusing, basically what my code does is, HelloWorld (C++) calls a method in sample (java), and sample (java) then calls a method in HelloWorld (C++).

Why do I do this? It’s just an exercise that was pretty helpful for me (I think) to understand the confusing thing that is JNI.

*bows*

Thoughts while reading Cocos2d-X by Example Beginner’s Guide Chapters 1 & 2

Packt published a new book on Cocos2d-X, “Cocos2d-X by Example Beginner’s Guide” by Roger Engelbert (http://www.packtpub.com/cocos2d-x-by-example/book)

Cocos2d-X by Example Beginner's Guide

First off, book cover is adorable.

Second, the book’s spiel says no programming knowledge required, oh really now? Anyway, I know Cocos2d, but I don’t know Cocos2dx nor C++, the language for Cocos2dx, so here I go. If I can make some cookie cutter games at the end of this review then…

I’m just going to spurt words while I read the blog and maybe give an overall summary and reviews at the end of this post. You can ignore the italicized parts, those are just random ramblings.

#nowplaying Lana Del Rey’s Young and Beautiful #onloop after watching “The Great Gatsby” last night.

Chapter 1 covers Installation. Installing Cocos2dx and whatnots.

The book assumes that you are on a Mac and you have Xcode, which yeah, I am and iOS dev and all, I have Xcode.

Okay, the book gives pretty clear instructions on where to download Cocos2dx. now, I just need a few minutes to download them.

Cram my Crash Course for Creativity assignment till then.

Okay, the instructions for installing are pretty clear. Although my Terminal had some other suggestions for how to properly install it. Anyway, that’s done. So when I create a new project in Xcode now I’ll be able to see the different Cocos2dx templates, awesome.

Just “built” and run my first Cocos2dx program, okay, the coconut head is silver and blue now. Looks kinda funky like Pepsi Blue.

Anyway, he did a brief run through on how to run the Cocos2dx samples so that we could see all the infinite possibilities, okay not really infinite, but it’s a pretty long list of sample tests.

And then, he says might need to spend some money on additional tools. He recommend and uses four tools.

TexturePacker, although you can also use Zwoptex as a free alternative. TexturePacker’s Andreas Löw actually used to offer (not sure if he still does, try tweeting him) licenses for bloggers. So yah, I have a free copy of TexturePacker.

ParticleDesigner, which will ease the process of making particles. No, I don’t have that. I’ll probably look for some free alternatives, the author didn’t mention or recommend any.

A tool to help build bitmap fonts, he recommended Glyph designer (not free), bmGlyph (cheaper, but yah, still not free) and FontBuilder (yeah, free). According to him “It is not extremely hard to build a Bitmap font by hand, not nearly as hard as building a particle effect from scratch, but doing it once is enough to convince you to get one of these tools fast.” Back in my Cocos2d days I used Hiero (free) and Photoshop (self advertise: blog on How to Make Fancy Labels using Cocos2d http://purplelilgirl.tumblr.com/post/2854271507/how-to-make-fancy-labels-using-cocos2d).

And according to him, no contest cfxr for sound effects. Free!

And we are done with Chapter 1. We installed Cocos2dx, and run a few sample projects and got to know the structure of basic Cocos2dx applications, so on to Chapter 2.

Chapter 2 gives an intro of C++ and Cocos2dx.

“This chapter will be aimed at two types of developers: the original Cocos2d developer who is scared of C++ but won’t admit it to his friends; and the C++ coder who never even heard of Cocos2d and finds Objective-C funny looking.”

I’m the first type, but I’m not afraid to admit that I’m afraid of C++. I am terrified of C++. If you give me an exam in C++, I will (and have, twice) submit an empty exam sheet (surprisingly passed one of those exams, I think the examiner took pity on account of my C++ phobia).

Can you tell that I’m stalling?

First the author goes through the basics of Cocos2d, if you know Cocos2d then you’re good to go. So far…

And then comes the dreaded C++ bits.

He says, “Don’t worry. The C part is easy, the first plus goes by really fast, but that second plus, Oh, boy.” Er… Oh boy…

I like the way the author talks in this book, kind of entertaining in a way.

He said to open your favorite text editor, because he doesn’t want code hinting and autocomplete features to get in the way. What? How did you think I finished a game in XNA without little knowledge in XNA, and completely zero knowledge in C#?! Code hinting and autocomplete, seriously.

My favorite text editor – TextEdit, because it comes bundled with a Mac. if I were on my PC laptop, I’d say Notepad, because that’s bundled there. I used to write websites in Notepad, those were the days… Yah, still stalling.

C++ syntax. Okay, so far, apprehensive.

Instantiation and Memory Management. Two words, no ARC. “so Objective-C developers who have forgotten memory management might have a problem here.” Uh oh.

The rule regarding memory management with C++ is very simple: if you new, you must delete.” Okay, I get that. And it supposedly has some other options and commands that’s similar to Objective C without ARC, okay.

 And then he continues with how to instantiate stuff. Okay, so far so good. And a little about the Cocos2dx equivalent of Objective C stuff. Okay, understood.

And summary. He says, “hopefully non C++ developers have learned that there is nothing to fear”. Um.. so far, not completely convinced, but I think I can manage.

He ends this chapter with “and furthermore Cocos2dx is awesome!” (fan boy) and “So let’s create a game already!”. 

Yes, lets. But maybe I’ll continue reading this tomorrow.

How to add Facebook to Unity Android?

I searched for this before, but couldn’t find a solution that was easy or cheap (by cheap, I mean free).

Pavel Kultyshev (@getencapsulated) also wrote a blog post, sharing messages on Twitter or Facebook by following the link in the browser of a mobile device or by opening the client app on this device. I haven’t tried this approach though, because I’m looking for something more “native” to Unity.

If you’d like an easy drag and drop solution and willing to spend, then there are a couple of available plugins: the aptly named Facebook Plugin for Android by Mida Mobile (for $20), Unishare, that also includes Twitter, LinkedIn, Sina Weibo, etc. (it’s $25, I don’t know how good it is, but for 5 more dollars you get way more social stuff, sounds pretty good), and of course, Prime31 also has one, it includes Twitter too (for $65 though).

Macaronics (phardera) also wrote a blog post on how to do this using Android Plugins: http://phardera.blogspot.tw/2013/04/unity-3d-facebook-sdk-for-android.html (it’s in Chinese though). Don’t worry, the entire project is available in phardera’s github (https://github.com/phardera/unity3d_fb_android).

New iOS and Android Books from Packt

iPhone JavaScript Cookbook

iPhone JavaScript Cookbook

Written by Arturo Fernandez Montoro

Overview of iPhone JavaScript Cookbook

  • Build web applications for iPhone with a native look feel using only JavaScript, CSS, and XHTML
  • Develop applications faster using frameworks
  • Integrate videos, sound, and images into your iPhone applications
  • Work with data using SQL and AJAX
  • Write code to integrate your own applications with famous websites such as Facebook, Twitter, and Flickr
  • These practical recipes include code and screenshots offering a clear step-by-step guide using different frameworks

Link: http://www.packtpub.com/iphone-javascript-cookbook/book/mid/170811hge054

Cocoa and Objective-C Cookbook

Cocoa and Objective-C Cookbook

Written by Jeff Hawkins

Overview of Cocoa and Objective-C Cookbook

  • Develop Cocoa applications using advanced UI concepts
  • Implement the latest Objective-C features and incorporate them into your applications
  • Debug Cocoa applications using advanced tools and techniques
  • Add advanced animation and multimedia to your Cocoa applications

Link: http://www.packtpub.com/cocoa-and-objective-c-cookbook/book/mid/170811c2v5x9

Core Data iOS Essentials

Core Data iOS Essentials

Written by B.M.Harwani

Overview of Core Data iOS Essentials

  • Covers the essential skills you need for working with Core Data in your applications.
  • Particularly focused on developing fast, light weight data-driven iOS applications.
  • Builds a complete example application. Every technique is shown in context.
  • Completely practical with clear, step-by-step instructions.

Link: http://www.packtpub.com/core-data-ios-essentials/book/mid/170811chs5cu

Flash Development for Android Cookbook

Flash Development for Android Cookbook

Written by Joseph Labrecque

Overview of Flash Development for Android Cookbook

  • The quickest way to solve your problems with building Flash applications for Android
  • Contains a variety of recipes to demonstrate mobile Android concepts and provide a solid foundation for your ideas to grow
  • Learn from a practical set of examples how to take advantage of multitouch, geolocation, the accelerometer, and more
  • Optimize and configure your application for worldwide distribution through the Android Market

Link: http://www.packtpub.com/flash-development-for-android-cookbook/book/mid/170811i8nwzh

Android Application Testing Guide

Android Application Testing Guide

Written by Diego Torres Milano

Overview of Android Application Testing Guide

  • The first and only book that focuses on testing Android applications
  • Step-by-step approach clearly explaining the most efficient testing methodologies
  • Real world examples with practical test cases that you can reuse

Link: http://www.packtpub.com/android-application-testing-guide/book/mid/170811fja1lj

Anyone interested in obtaining a free review copy in order to review the book in preferably under 2 weeks time can contact Packt’s online marketing representative Shaveer at shaveeri@packtpub.com with the subject line “book name- review request”. It can be for more than 1 book as well.