Archive for the ‘Unity 3D’ Category

Extending the Unity 3D Editor

The Horseman has found that one of the most interesting aspects of Unity 3D is that one is able to extend the authoring tool, such that one can add new functionality, menus, and behaviors to optimize workflow.

Those of you who remember a certain entry about using JSFL to automate build processes in the Flash environment may already have an idea of what I’m talking about, but extending the Unity editor is actually much easier because the same code used to write and script object behavior at runtime in the player can also be used inside the editor itself. This would be as though you were able to write extentions for the Flash authoring tool using ActionScript 3, instead of JSFL. That would be simply huge.

Fortunately, getting started with extending the Unity Editor is relatively straightforward, but unfortunately there is scant documentation on what is possible, and the samples on Unity’s website currently feature only Unity’s JavaScript and not C#. Fortunately for you, the Horseman can shed at least a little light on the subject, so follow along with this tutorial. For those who want the final source project right away, you can download the source here. I am currently using Version 3.3.0f4 of Unity on Windows, and have also tested this on Mac OSX.

First, open the Unity editor and in your “Project” panel create the following folder structure:

- Assets
  + Editor
- Scenes
- Scripts

Create a folder called Assets, with a subfolder called Editor. This is where our editor scripts must live in order for Unity to use them. Scenes is where we will save our Unity Scene, and Scripts is where we will keep our GameObject classes.

First, we need to create our Scene. Simply select File -> Save Scene As… and save the current scene with the name “MyScene”. You will now see “MyScene” in the project panel, so move it into the Scenes folder now.

Next, we’re going to start by creating a GameObject script. For the sake of argument, let’s say we want to write a C# script that, when called, will instantiate a GameObject that represents a simple four-vertex plane. We’ll call it “PunyPlane” for now, so in your “Scripts” folder, right-click and choose Create -> C Sharp Script. Rename this script to be named “PunyPlane”, then replace the code inside with the following, and save:

/* *
 *  This class creates a small, 4 vertex plane.  
 *  It's provided purely for instructional purposes,
 *  as an example of how one can instantiate custom 
 *  GameObjects with graphical representations.
 *  It is not necessary to understand how this code
 *  works, but feel free to study it if you wish
 *  to get a small taste of how polygons and planes
 *  are created procedurally in Unity.
 * */
using UnityEngine;
using System.Collections;
public class PunyPlane : MonoBehaviour {
	public static Material sharedMaterial;
	/* *
	 * Call Create without parameters to return a PunyPlane of 1 x 1 world units.
	 * */
	public static PunyPlane Create(){
		return Create(1.0f,1.0f);
	/* *
	 * Call Create with a height and width expressed in world units.
	 * */
	public static PunyPlane Create(float width, float height){
		/* *
		 * We start by creating a GameObject to represent our plane,
		 * giving it the requisite components in order to accomplish
		 * this goal, a <MeshFilter> and a <MeshRenderer>.
		 * */
		GameObject go = new GameObject(); = "PunyPlane";
		MeshFilter mf = go.AddComponent<MeshFilter>();
		MeshRenderer mr = go.AddComponent<MeshRenderer>();
		/* *
		 * Now it's time to create our PunyPlane component.  
		 * */
		PunyPlane pp;		
		pp = go.AddComponent<PunyPlane>() as PunyPlane;
		if(mf.sharedMesh == null){
			mf.sharedMesh = new Mesh();
		Mesh mesh = mf.sharedMesh;
			Here is a diagram of our plane,
			with the verts labeled. 
		 0    3
		  | /|
		  |/ |
		 1    2		 
		Vector3 p0 = new Vector3(-width * 0.5f, -height * 0.5f,0);
		Vector3 p1 = new Vector3(-width * 0.5f, height * 0.5f,0);
		Vector3 p2 = new Vector3(width * 0.5f, height * 0.5f,0);
		Vector3 p3 = new Vector3(width * 0.5f, -height * 0.5f,0);
		/* *
		 * Make sure the Mesh is cleared of all old data, then 
		 * apply the new verts and triangles in order to form
		 * a square plane.
		 * */
		mesh.vertices = new Vector3[]{p0,p1,p2,p3};
		mesh.triangles = new int[]{
		/* *
		 * And we'll want to set up the uv coordinates to match
		 * the verts listed above.  This is so the plane can wear
		 * a texture without it appearing mangled, flipped, or 
		 * inverted.
		 * */
		mesh.uv = new Vector2[]{
			new Vector2(0,0),
			new Vector2(0,1),
			new Vector2(1,1),
			new Vector2(1,0)
		/* *
		 * Using "Unlit/Texture" because of the assumption that 
		 * this will be a flat, 2D sprite and will not need to 
		 * be affected by things like lighting.  This will make
		 * the plane render more efficiently.
		 * */
		if(sharedMaterial == null)sharedMaterial = new Material(Shader.Find("Unlit/Texture"));
		mr.sharedMaterial = sharedMaterial;
		mr.sharedMaterial.shader = Shader.Find("Unlit/Texture");
		return pp;

The above script allows us to dynamically generate a plane in 3D space by calling PunyPlane.Create(), for a 1×1 plane, or PunyPlane.Create(width,height) for a variable sized plane. Note that this code does not correct for negative width / height values.

To test this code, let’s give it somewhere to run. We’re going to create a “GameManager” object in our heirarchy, that will contain a “GameManager.cs” component that kicks off and runs our game logic. In this case, it won’t be very exciting logic. It will merely instantiate some of our PunyPlane objects. Go to the toolbar and select GameObject -> Create Empty. This will create a new, empty GameObject in your Heirarchy. Rename this GameObject as “GameManager”. You’ll also create another empty GameObject, and rename it as “World.”

Next, right-click your Scripts folder, and create a new C# script. Rename it as “GameManager”. Next, select the GameManager object in your heirarchy, and then drag the GameManager script over to the “Inspector” panel for the GameManager object (The “Inspector” is the panel where you can set the object’s Transform positions in world space.)

Now, we’re going to open the GameManager.cs script file and write the following code:

/* *
 * The GameManager kicks off all of our game logic.  In this case, there isn't much logic.
 * We simply instantiate a few PunyPlane objects and place them in the heirarchy.
 * Assuming that this code has been added as a component to one of the GameObjects in the
 * Heirarchy, this should take effect when you press "Play" or when you view the compiled
 * application in the Unity player.
 * */
using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour {
	void Start () {
		// This creates a PunyPlane instance that lives on the 
		// top level of the heirarchy.
		PunyPlane punyPlane = PunyPlane.Create();
		// Let's add a 0 to this instance's name 
		// in order to differentiate it from its kin. = + "0";
		// Now let's make a new PunyPlane, giving it
		// an uneven rectangular shape, and give it
		// a distinctive name.
		punyPlane = PunyPlane.Create(3.0f, 0.5f); = + "1";		
		// Add the new PunyPlane to the World.  This removes it
		// from the top level of the heirarchy.  First, find the 
		// "World", then add the plane's transform as a child
		// to the world's transform.
		GameObject world = GameObject.Find("World");
		punyPlane.gameObject.transform.parent = world.transform;
		// Finally, we offset this new PunyPlane
		// just a bit, so we can see them both on the screen.
		punyPlane.transform.position = new Vector3(0,1.5f,0);

Now save the script file. All this Manager script does is instantiate two PunyPlane object in our game, dynamically at runtime. Press the Play button to preview the game. If you have performed the steps correctly, you should see two planes appear in the Game window. Once you stop the game, these planes will disappear, as they only exist at runtime.

I already know what you’re thinking. But Mr. Horseman! What does any of this have to do with extending the Unity editor? All we’re doing is creating planes at runtime!

Little do you realize dear reader, that is in fact the magic of what we’re about to do next! It’s nice to be able to generate dynamic planes at runtime, but wouldn’t it be even nicer if we could just treat this plane like a Unity primitive and instantiate it inside the Editor instead of just in the player at runtime? That way we don’t have to rely on the bloated 121 vert / 200 triangle plane that Unity supplies as a primitive. Well, get ready to blow your own mind. Inside the “Assets/Editor” folder (specifically inside Editor), right-click and create a new C# file. Rename it as “CustomToolBar”, then open the file in your text editor and replace it with the following code, then save:

/* *
 * CustomToolBar is used to add some new functionality to the Unity3D Editor.  
 * In this case we're going to add some menu items to the top level toolbar.
 * */
using UnityEngine;
using UnityEditor;
using System.Collections;
public class CustomToolbar : MonoBehaviour {
	/* *
	 * The following two methods are added to the Unity default toolbar,
	 * as sub-menus under the GameObject dropdown.  It should appear at 
	 * the very bottom of the GameObject dropdown list.
	 * GameObject ->
	 * 		Primitives (We made this one) ->
	 * 			Create XXX
	 * */
	[MenuItem ("GameObject/Primitives/Create PunyPlane in Heirarchy")]
	public static void MakePunyPlane(){
		// This function simply creates a PunyPlane in the top level of the
		// Heirarchy.
	[MenuItem ("GameObject/Primitives/Create PunyPlane As Child of Selection")]
	public static void MakePunyPlaneAsChildOfSelection(){
		// We start by creating a PunyPlane in the top level of the 
		// Heirarchy.
		PunyPlane pp = PunyPlane.Create();
		// And if we've got a GameObject currently selected in the 
		// heirarchy, we'll reparent the PunyPlane to our selected
		// object.
			pp.gameObject.transform.parent = Selection.activeGameObject.transform;
	/* *
	 * And finally, we create a brand new menu item in the Unity editor.
	 * This will actually appear as a new top-level item called "Scriptocalypse"
	 * with a command "Say Hello".  The "Scriptocalypse" item should appear 
	 * between "Terrain" and "Window".
	 *   Scriptocalypse ->
	 * 		Say Hello
	 * */
	[MenuItem ("Scriptocalypse/Say Hello")]
	public static void SayHello(){
		Debug.Log("Hello from the Unity3D toolbar.");	

As a reference, your project’s file and asset structure should look like this:

Assuming there are no errors in any of the above scripts, when you click back onto the Unity Editor you should immediately notice that the toolbar at the top has a new entry between “Terrain” and “Window” that was never there before. It should be called “Scriptocalypse”, and inside is a menu with a single option, “Say Hello”. Clicking this option sends a message to the Debugger, as you can see.

But Mr. Horseman, what about those functions that let you create planes in the editor? Where are they?

Aaah, notice in the code sample above that we have some braces that contain some interesting code? Look at the very first function and its brace block:

[MenuItem (“GameObject/Primitives/Create PunyPlane in Heirarchy”)]

That string represents the path to the menu item we’ve created, so as you can see we’ve simply added a new option to the pre-existing GameObject menu item. At the bottom, you should find “Primitives”, which has two functions. The first of them simply adds a new PunyPlane to the Heirarchy. The second will go a step further, and add the PunyPlane to whichever game object is currently selected in the Heirarchy. Go ahead, and try them out.

Do you see the magic here? The same code we use to create and manipulate behaviors at runtime is also the code we use to instantiate scripts in the editor! Such sorcery is simply not known in the lands of Flash, which makes it all the more exciting to actually see in action here.

You’ll notice that the PunyPlane instances we create actually have the PunyPlane component attached to the GameObject. This is by design. We currently have no special behaviors or public properties attached to the PunyPlane component, but we may soon in another posting. We’ll find that public properties are exposed in the inspector, and can be set both at runtime and in the editor… but what about public getter/setter pairs? Aaaah, in C# those are not exposable in the inspector… at least not without a bit of trickery! The Horseman will leave you pondering just what manner of trickery until then, but suffice it to say there are a few ways.

In the meantime, Download the Unity project and source files for this tutorial if you need any assistance.

Tags: , ,


Reports from the field – Alien Apartment demo on more devices

On the 12th of April, I gave a very short presentation of my Alien Apartment demo (apk) to a local Android Developer meetup group.

One of the attendees was so kind as to grab the apk that very night and show me how it runs on some other devices. He demoed it running on the Samsung Galaxy Tab, and the Motorola Xoom. The excellent news is that the UI repositions as I’d expected. This was possibly the thing that worried me most, and I was gratified to see it went according to plan. The even better news is that the Galaxy Tab ran the demo so very incredibly smoothly. The animations were smooth as butter, and the controls were very responsive. The framerate felt almost as nice as the web player version. Furthermore, the larger screen size made the whole control scheme feel very nice and open. On my phone it can feel a little cramped, but not so on the larger screen. Performance on the Xoom seemed subjectively to be about 2/3 that of the Galaxy Tab, which is surprising given its raw statistics.

I’d like to thank Mike for letting me see the demo running on another device in-person, and if anyone else (whether you attended the meetup or not) has anything to report on how the demo runs on a device, please let me know.

Tags: , ,

1 Comment

Alien Apartment Update

This is possibly the last chance I’ll have to work on the Unity 3D demo for a while, so I decided I’d make this update a good one. Here is the web playable version and here is the apk. You’ll notice a few things different between the web playable version and the APK even though they are compiled from the same source. Not all these differences are intentional. Here’s a breakdown of the differences you’l see:

  • Intentional: The apk has onscreen controls for the character
  • Unintentional: The web version shows both a health meter and a rage meter. The apk only shows health
  • Unintentional: The robot enemies in the courtyard have a solid purple helmet in the apk. In the web version you can see that the helmets are clear glass.
  • Unintentional: The player’s character in the web version has a different jump height outdoors than indoors. This was the intended effect. In the apk, the player’s jump height is locked to the very first value known. Since you start in the apartment, the jump height will be very small.

I suspect that the rage meter problem has something to do with the fact that the health / rage meters make use of the native GUI elements (which means that under the hood they’re using OnGUI, which is a shame). As of now I can’t quite explain why the robot’s helmet has lost its texture in the apk. The texture existed until Unity crashed on me and I had to restart it. After the crash, the helmet texture disappeared from the apk and the preview editor. As you can see though, it continues to exist in the web player.

As I mentioned in my previous post, there were a number of code optimizations I implemented, which gained me about 5fps on-average. If I had to take a stab at what causes most of the slowdowns it would have to be that these particular scenes are somewhat heavy in terms of mesh construction and lighting. It’s no problem at all for a desktop (at least a Windows desktop) or a modern laptop, but mobile requires a lighter touch with its models. It doesn’t help that the cameras render a great deal of the field as well.

For more information on using Unity for mobile devices, check out this presentation which shows some additional best practices as well as a particularly impressive example of how an intelligent approach to laying out a scene allows you to squeeze maximum performance out of a Unity mobile project. Do not miss the part of the video where the representative of Crecent Moon Games presents Aralon: Sword and Shadow, which showcases the incredible potential of Unity.

As for myself, I’m suitably impressed by the Unity tool. It renders the code aspect quite easy to work with, as you can program at a much higher level of abstraction than using OpenGL directly, and while the drag-and-drop relationships of the code with the on-screen assets can seem muddy if you come from a strict OOP background it’s possible to create a well-designed structure regardless. The biggest hurdle with Unity, and the one that there is no truly easy solution for, is that 3D assets such as models, animations, and textures are incredibly labor intensive to create. It’s a much bigger field with many more areas of specialization than 2D art. You may or may not have noticed, but almost all the art assets from this project are either from Unity’s own site or otherwise royalty-free. The time investment for 3D assets is the biggest reason why. This example, which constitutes my first forray into simply learning my way around the Unity tool took approximately three weeks of my time, where the only art assets I generated were the A/B buttons in the APK and the titlescreen. Were I to create my own 3D assets, this demo would not even exist in the span of three weeks.

No Comments