* You are viewing the archive for the ‘Programming’ Category

Using Iggy for Flash Animation in Unity3D

Recently, we have been looking into technologies that allow integration of animations made in Flash in Unity3D prototypes and games. This seems to be very useful to create complex 2D animations in Flash, and simply play them in Unity.

There are a several solutions on the market for this, like AutoDesk’s Scaleform, UniSWF and Rad Game Tools’ Iggy. Since I wasn’t able to obtain a trial version of both Scaleform (which wasn’t yet released for Unity) and UniSWF (whose support didn’t answer to our email), I have examined Iggy in more detail.

We were quite surprised to see that Iggy gives you the freedom to program parts of your game either in Unity, or in Flash itself, using ActionScript 3. For instance, you could write a lot of actionscript code for the animation and simply dispatch input events like a key press through Iggy to the actionscript. Alternatively, you could limit the code in Flash as much as possible, and control everything from within Unity.

This sounds quite powerful, but unfortunately the process required to integrate it in a project can’t really be called user friendly. It seems that this still requires a lot of code that could as well have been hidden from the programmer’s eyes. Also on the stability side of the product, there’s still some work for Rad Game Tools – Unity crashed now and then while playing Flash animations.

Iggy is still relatively new and still has some issues, but it’s certainly something to look out for. I may have a second look at it again in a few months from now, and also evaluate Scaleform and UniSWF if possible.

2D Game Development in Unity3D: Overview

Continuing our series about 2D development and prototyping in Unity3D, we’re back with an overview of the different methods and their pros and cons.

Unity3D’s GUI class (previous post)

Pros:

  • Very fast to use: only line of code is enough to display an image – no other actions or setup involved.
  • Images can be displayed in a ‘pixel-perfect’ way.
Cons:

  • Bad performance on iOS: not suitable for if more than 30-50 have to be simultaneously visible on screen (each image consumes one draw call).
  • Using the physics engine is not possible without a workaround.
  • Additional code is required to support different screen resolutions.

Sprite manager systems like GUISpriteUI (previous post)

Pros:

  • Fast on iOS: textures can be easily combined into texture Atlases, potentially resulting in only one draw call.
  • Images can be displayed in a ‘pixel-perfect’ way.
  • Most systems allow positioning sprites in the editor.
Cons:

  • Slower to use: more code writing and setup involved.
  • Using the physics engine is not possible without a workaround.
  • Depending on the system used, additional code may be required to support different screen resolutions.

3D objects and orthographic projection (previous post)

Pros:

  • Allows using the Unity3D editor to build your levels.
  • Relatively fast UI on iOS and Android.
  • Easy access to the physics engine.
  • Easy to combine with other Unity3D features (e.g. particle effects, 3D animated characters and animation blending, …).
  • Your game automatically works under different screen resolutions.
Cons:

  • Performance can be optimized on iOS by using texture atlases, but requires additional setup.
  • Using pixel coordinates to define the scale and position of objects is possible, but makes it a lot harder (or impossible) to get decent results from the physics engine.

As you can see, each of them has its own specific advantages and disadvantages. This means there is no ‘best’ method; all depends on the needs of your project.

2D Game Prototyping in Unity3D: Orthographic Projection

After having discussed Unity3D’s GUI class and the GUISpriteUI system as two different methods of creating 2D games in Unity3D, we’re now ready to discuss a third method: combining 3D graphics with orthographic projection.

For this to work, you’ll have to create a scene in 3D, and then set up the camera to use orthographic projection instead of perspective projection.

If all you want is to use 2D textures, you can simply create cubes and assign them materials with these textures.

The fact you’re using a 3D engine to create your 2D graphics actually allows you to do more than that; the possibilities include using the physics engine, or use 3D animation blending for your characters.

To set up your camera correctly, you have to set Projection to Orthographic, and you have to set the Orthographic Size.

Especially in prototypes where the physics engine needs to be used, this can come in very handy. The following video gives you a peek behind the scenes of the Gremlin and Bayou Bird prototypes:

The fifth and last post in this series about achieving 2D in Unity3D will summarize the advantages and disadvantages of the different methods, so you’ll know which method to choose depending on your needs.

2D Game Prototyping in Unity3D: Sprite Manager Systems

As I explained in my previous post, usage of Unity3D‘s built-in GUI class can be a real performance killer on the iOS and Android platforms due to the high amount of draw calls.

Using a Sprite Manager system, such as GUISpriteUI, this performance issue can be entirely resolved.

To reduce the high number of draw calls, you could generate a 3D mesh on the fly, containing all separate rectangles for your 2D graphics. This mesh can then be sent to the GPU in a single draw call, along with one big texture atlas containing all your 2D images.

This is exactly what a system like GUISpriteUI is doing. It dramatically reduces the number of draw calls (perfect for iOS and Android), but requires some set-up effort.

Unfortunately, every advantage has its disadvantage, and this isn’t different for the GUISpriteUI system.

In order to make it work, you’ll need some additional time to set up this system. Also, you’ll have to create a sprite object for each image you want to show, making it slower to use. I’m sure this may be no big deal when implementing a full game, but when prototyping, this is slowing you down.

We can conclude that this system is perfect for 2D UI in both 2D and 3D games, but that it’s less interesting to use for rapid prototyping.

2D Game Prototyping in Unity3D Using the GUI Class

Using the GUI class is probably the simplest way to create 2D game prototypes in Unity3D.

To draw an image to the screen, you only need a single line of code; no objects need to be instantiated whatsoever:

GUI.DrawTexture((Texture2D)Resources.Load("bunny"));

For this to work, this line needs to be in the OnGUI method, and a file named bunny has to exist in the Assets/Resources folder (the actual file would be named bunny.png, bunny.psd, or whatever your favorite file format is).

For many uses, this is fast enough.

When you’re drawing many images every frame, there’s some room for optimization:

  • The OnGUI method is called multiple times per frame (once for each input event, and once for the rendering). As we’re only drawing a texture here, it’s enough to draw the texture only when rendering.
  • Also, Resources.Load is called each time. This doesn’t mean our bunny is loaded from disk all the time; instead, it’s only loaded the first time, and loaded from cache every subsequent time. Still, the cached data is retrieved every time by string – a relatively slow operation.

So in case the GUI code is getting slow, you could try the following:

// in your class declaration
Texture2D bunny;
 
// in Start()
 bunny = (Texture2D)Resources.Load("bunny");
 
// in OnGUI()
if (Event.current.type == EventType.Repaint)
{
	GUI.DrawTexture(bunny);
}

Using the GUI class has a major drawback on iOS and Android: each image or text string is sent separately to the GPU, resulting in many draw calls. As these are really slow operations on mobile platforms, this is a real performance killer.

An other drawback is that you won’t be able to use the built-in physics engine. Depending on what you want to prototype, this may be an issue.

In the next post, I’ll discuss how sprite manager systems, such as GUISpriteUI, can be used to get faster 2D graphics on mobile platforms.

Prototyping 2D Games in Unity3D

For many of our prototypes, we’re using Unity3D. Even if the gameplay is 2D.

There are several different ways to create 2D games and prototypes in Unity3D.
In the posts I’ll make the following days, I’ll be commenting on three possible solutions:

  • Using Unity3D’s GUI class
  • Using a sprite manager system, such as GUISpriteUI
  • Using 3D objects and orthographic projection

A peek behind the scenes of the Gremlin prototype

Unity and PlayMaker: The best of both worlds

Following-up on my brief review of PlayMaker, I’m back to explain you about how PreviewLabs may use PlayMaker in the future.

As I concluded before, the best part of PlayMaker can give you nice visual overview of a finite-state machine (FSM), an oft used construct in rapid game prototyping.
This overview is something you surely don’t have when implementing a FSM in code.

However, from a programmer’s point of view, it’s quite clumsy to use PlayMaker to add behavior to the FSM’s states.

The solution is to take the best of both worlds: creating states and connecting them using PlayMaker, and writing the states’ behavior in your favorite Unity programming language.

To be able to do this, you have to add events in PlayMaker’s FSM Editor. These events can be used to add the state transitions in a visual way, and can be raised in your code.

The following is an example state class to use with PlayMaker:

using UnityEngine;
using HutongGames.PlayMaker;
 
public class Idle : MonoBehaviour {
 
	private PlayMakerFSM fsm;
 
	// Use this for initialization
	public virtual void Start () {
		// Initialize the behavior
		fsm = (PlayMakerFSM)gameObject.GetComponent(typeof(PlayMakerFSM));
	}
 
	// Update code goes here
	public virtual void Update() {
		// Call this to raise the event of your choice
		fsm.Fsm.Event("FINISHED");
	}
}

To add this code to a state, you need to add a ScriptControl Action in the FSM Editor, and then add a script.

Feel free to comment to this post and share your experiences!

Research: PlayMaker

As part of our technology research project, I have been investigating PlayMaker, a plug-in for Unity3D which allows you to create finite-state machines (FSMs) in a visual way.


Finite-state machines (FSMs) divide logic in a finite number of states. They are great for most prototypes as they allow writing complex behaviors in a single class, while keeping the code clean. Because PreviewLabs is using FSMs quite extensively, I thought it would be interesting to have a closer look at PlayMaker.

The PlayMaker plug-in allows you to add a FSM component to any Unity3D GameObject, and define the states and their logic in a visual way, using the FSM Editor.

On the left side of the editor, you can see the states of the FSM. At the right, you see the actions defined for the selected state. Most of these actions allow you to access the Unity API functionality, but you can also write your own actions.

Because FSMs are perfectly suited to implement AI, I used PlayMaker to make a simple game where the player has to avoid being shot by a cannon. PlayMaker allowed me to get a quick first result, but as the game evolved and got more complicated, the series of actions got more complicated too.

While you would expect visual programming to give you a better overview of your game logic, implementing the behavior for the states was a very confusing experience. To be honest, it’s a lot easier to write code to implement this – at least from a programmer’s point of view.

Is PlayMaker then all bad for us? No, the one thing I really find interesting and useful is that it can give you a visual overview of a FSM and its transitions, while allowing you to change the FSM by linking states in a different way.

In a next blog post, I will explain you more about how you can get the best from both worlds.

Writing PlayerPrefs, Fast

An other way of saving data in Unity3D in a platform-independent way is to use the PlayerPrefs class.
This class works like a hash table, allowing you to store key-value pairs.

The disadvantage of the built-in PlayerPrefs class is that it’s really slow on iOS and even slower on Android. During a test we did on a Google Nexus One, we saved only 6.25 key-value pairs per second. Because we were trying to save over 300 records, this took way too long. Most likely, they are doing file I/O operations for every modification. The current PlayerPrefs class is clearly not designed to handle a larger amount of data.

So we decided to implement our own version of the PlayerPrefs class, allowing faster saving of tuning parameters in our prototypes. Now we’re saving 300+ records almost instantly on on the same device.

If you’re already using the Unity PlayerPrefs class in your project, and you’re looking for an optimization on iOS and Android devices, you can do the following:

  • Download our PlayerPrefs.cs file and add it to your project.
  • Add the following line at the beginning of the files in which PlayerPrefs is used:
    using PlayerPrefs = PreviewLabs.PlayerPrefs;
  • Use PlayerPrefs.Flush() to save all values. This can be done after writing a bunch of data, or when the application is quit (in your main game class):
    public void OnApplicationQuit()
    {
    	PlayerPrefs.Flush();
    }

To obtain this optimization, we’re keeping a Hashtable and only writing it to a file when Flush() is called.
We’re deliberately not using an XML format to do this, as this would create an overhead unwanted on these lower-end devices.

File I/O in Unity3D

At the moment, there is no platform-independent way to save data in Unity3D.

If you want to open a file for reading or writing, you need to use the proper path. This code will do the trick and works on PC, Mac, iOS and Android:

       string fileName = "";
#if UNITY_IPHONE			
	string fileNameBase = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf('/'));
	fileName = fileNameBase.Substring(0, fileNameBase.LastIndexOf('/')) + "/Documents/" + FILE_NAME;
#elif UNITY_ANDROID
	fileName = Application.persistentDataPath + "/" + FILE_NAME ;
#else
	fileName = Application.dataPath + "/" + FILE_NAME;
#endif
 
fileWriter = File.CreateText(fileName);
fileWriter.WriteLine("Hello world");
fileWriter.Close();

[edit]

Since Unity 3.3, it is no longer necessary to use platform-specific code for simple file I/O. Use Application.persistentDataPath to do the trick.

This code would replace the code above:

	string fileName = Application.persistentDataPath + "/" + FILE_NAME;
	fileWriter = File.CreateText(fileName);
	fileWriter.WriteLine("Hello world");
	fileWriter.Close();

Thanks, erique, for pointing this out on the Unity forum.

[/edit]