Unity Manual

Welcome to Unity.

Unity is made to empower you to create the best interactive entertainment or multimedia experience that you can. This manual is designed to help you learn how to use Unity, from basic to advanced techniques. It can be read from start to finish or used as a reference.

The manual is divided into different sections. The first section, User Guide, is an introduction to Unity's interface, asset workflow, and the basics of building a game. If you are new to Unity, you should start by reading the Unity Basics subsection.

The iOS Guide addresses iOS specific topics such as iOS-specific scripting API, optimizations, and general platform development questions.

The Android Guide addresses Android specific topics such as setting up the Android SDK and general development questions.

The next section, FAQ, is a collection of frequently asked questions about performing common tasks that require a few steps.

The last section, Advanced, addresses topics such as game optimization, shaders, file sizes, and deployment.

When you've finished reading, take a look at the Reference Manual and the Scripting Reference for further details about the different possibilities of constructing your games with Unity.

If you find that any question you have is not answered in this manual please ask on Unity Answers or Unity Forums. You will be able to find your answer there.

Happy reading,
The Unity team

The Unity Manual Guide contains some sections that apply only to certain platforms. Please select which platforms you want to see. Platform-specific information can always be seen by clicking on the disclosure triangles on each page.

Table of Contents

Page last updated: 2013-09-20



User Guide

This section of the Manual is focused on the features and functions of Unity. It discusses the interface, core Unity building blocks, asset workflow, and basic gameplay creation. By the time you are done reading the user guide, you will have a solid understanding of how to use Unity to put together an interactive scene and publish it.

We recommend that new users begin by reading the Unity Basics section.

Page last updated: 2010-09-09



Unity Basics

This section is your key to getting started with Unity. It will explain the Unity interface, menu items, using assets, creating scenes, and publishing builds.

When you are finished reading this section, you will understand how Unity works, how to use it effectively, and the steps to put a basic game together.

Page last updated: 2013-07-12



Learning the Interface

Take your time to look over the Unity Editor interface and familiarize yourself with it. The Main Editor Window is made up of several Tabbed Windows, called Views. There are several types of Views in Unity - they all have specific purposes which are described in the subsections below.

Page last updated: 2013-05-29



ProjectView40

In this view, you can access and manage the assets that belong to your project.

The left panel of the browser shows the folder structure of the project as a hierarchical list. When a folder is selected from the list by clicking, its contents will be shown in the panel to the right. The individual assets are shown as icons that indicate their type (script, material, sub-folder, etc). The icons can be resized using the slider at the bottom of the panel; they will be replaced by a hierarchical list view if the slider is moved to the extreme left. The space to the left of the slider shows the currently selected item, including a full path to the item if a search is being performed.

Above the project structure list is a Favorites section where you can keep frequently-used items for easy access. You can drag items from the project structure list to the Favourites and also save search queries there (see Searching below).

Just above the panel is a "breadcrumb trail" that shows the path to the folder currently being viewed. The separate elements of the trail can be clicked for easy navigation around the folder hierarchy. When searching, this bar changes to show the area being searched (the root Assets folder, the selected folder or the Asset Store) along with a count of free and paid assets available in the store, separated by a slash. There is an option in the General section of Unity's Preferences window to disable the display of Asset Store hit counts if they are not required.

Along the top edge of the window is the browser's toolbar.

Located at the left side of the toolbar, the Create menu lets you add new assets and sub-folders to the current folder. To its right are a set of tools to allow you to search the assets in your project.

The Window menu provides the option of switching to a one-column version of the project view, essentially just the hierarchical structure list without the icon view. The lock icon next to the menu enables you to "freeze" the current contents of the view (ie, stop them being changed by events elsewhere) in a similar manner to the inspector lock.

Searching

The browser has a powerful search facility that is especially useful for locating assets in large or unfamiliar projects. The basic search will filter assets according to the text typed in the search box

If you type more than one search term then the search is narrowed, so if you type coastal scene it will only find assets with both "coastal" and "scene" in the name (ie, terms are ANDed together).

To the right of the search bar are three buttons. The first allows you to further filter the assets found by the search according to their type.

Continuing to the right, the next button filters assets according to their Label (labels can be set for an asset in the Inspector). Since the number of labels can potentially be very large, the label menu has its own mini-search filter box.

Note that the filters work by adding an extra term in the search text. A term beginning with "t:" filters by the specified asset type, while "l:" filters by label. You can type these terms directly into the search box rather than use the menu if you know what you are looking for. You can search for more than one type or label at once. Adding several types will expand the search to include all specified types (ie, types will be ORed together). Adding multiple labels will narrow the search to items that have all the specified labels (ie, labels are ANDed).

The rightmost button saves the search by adding an item to the Favourites section of the asset list.

Searching the Asset Store

The Project Browser's search can also be applied to assets available from the Unity Asset Store. If you choose Asset Store from the menu in the breadcrumb bar, all free and paid items from the store that match your query will be displayed. Searching by type and label works the same as for a Unity project. The search query words will be checked against the asset name first and then the package name, package label and package description in that order (so an item whose name contains the search terms will be ranked higher than one with the same terms in its package description).

If you select an item from the list, its details will be displayed in the inspector along with the option to purchase and/or download it. Some asset types have previews available in this section so you can, for example, play an audio clip or rotate a 3D model before buying. The inspector also gives the option of viewing the asset in the usual Asset Store window to see additional details.

Shortcuts

The following keyboard shortcuts are available when the browser view has focus. Note that some of them only work when the view is using the two-column layout (you can switch between the one- and two-column layouts using the panel menu in the very top right corner).

FFrame selection
TabShift focus between first column and second column (Two columns)
Ctrl/Cmd + FFocus search field
Ctrl/Cmd + ASelect all visible items in list
Ctrl/Cmd + DDuplicate selected assets
DeleteDelete with dialog
Delete + ShiftDelete without dialog
Backspace + CmdDelete without dialogs (OSX)
EnterBegin rename selected (OSX)
Cmd + down arrowOpen selected assets (OSX)
Cmd + up arrowJump to parent folder (OSX, Two columns)
F2Begin rename selected (Win)
EnterOpen selected assets (Win)
BackspaceJump to parent folder (Win, Two columns)
Right arrowExpand selected item (tree views and search results). If the item is already expanded, this will select its first child item.
Left arrowCollapse selected item (tree views and search results). If the item is already collapsed, this will select its parent item.
Alt + right arrowExpand item when showing assets as previews
Alt + left arrowCollapse item when showing assets as previews

Page last updated: 2012-11-15



Hierarchy


The Hierarchy contains every GameObject in the current Scene. Some of these are direct instances of asset files like 3D models, and others are instances of Prefabs, custom objects that will make up much of your game. You can select objects in the Hierarchy and drag one object onto another to make use of Parenting (see below). As objects are added and removed in the scene, they will appear and disappear from the Hierarchy as well.

Parenting

Unity uses a concept called Parenting. To make any GameObject the child of another, drag the desired child onto the desired parent in the Hierarchy. A child will inherit the movement and rotation of its parent. You can use a parent object's foldout arrow to show or hide its children as necessary.


Two unparented objects

One object parented to another

To learn more about parenting, see the Transform Component page.

Page last updated: 2013-10-10



Toolbar

The Toolbar consists of five basic controls. Each relate to different parts of the Editor.

Transform Tools -- used with the Scene View
Transform Gizmo Toggles -- affect the Scene View display
Play/Pause/Step Buttons -- used with the Game View
Layers Drop-down -- controls which objects are displayed in Scene View
Layout Drop-down -- controls arrangement of all Views

Page last updated: 2012-10-17



SceneView43

The Scene View is your interactive sandbox. You will use the Scene View to select and position environments, the player, the camera, enemies, and all other GameObjects. Maneuvering and manipulating objects within the Scene View are some of the most important functions in Unity, so it's important to be able to do them quickly. To this end, Unity provides keystrokes for the most common operations.

Scene View Navigation

See Scene View Navigation for full details on navigating the scene view. Here's a brief overview of the essentials:

You might also find use in the Hand Tool (shortcut: Q), especially if you are using a one-button mouse. With the Hand tool is selected,

Click-drag to drag the camera around.
Hold Alt and click-drag to orbit the camera around the current pivot point.
Hold Control (Command on Mac) and click-drag to zoom the camera.

In the upper-right corner of the Scene View is the Scene Gizmo. This displays the Scene Camera's current orientation, and allows you to quickly modify the viewing angle.

Each of the coloured "arms" of the gizmo represents a geometric axis. You can click on any of the arms to set the camera to an orthographic (i.e., perspective-free) view looking along the corresponding axis. You can click on the text underneath the gizmo to switch between the normal perspective view and an isometric view. While in isometric mode, you can right-click drag to orbit, and Alt + middle-click drag to pan.

Note that the Scene Gizmo will be hidden when the view is in 2D mode, since the view is always directly at the XY plane.

Positioning GameObjects

See Positioning GameObjects43 for full details on positioning GameObjects in the scene. Here's a brief overview of the essentials:

When building your games, you'll place lots of different objects in your game world. To do this use the Transform Tools in the Toolbar to Translate, Rotate, and Scale individual GameObjects. Each has a corresponding Gizmo that appears around the selected GameObject in the Scene View. You can use the mouse and manipulate any Gizmo axis to alter the Transform Component of the GameObject, or you can type values directly into the number fields of the Transform Component in the Inspector.

Scene View Control Bar

The control bar lets you choose various options for the scene view. You can switch on or off the audio, lighting and 2D mode and also control how objects, image effects and gizmos will be displayed. See the View Modes43 section for further details.

Page last updated: 2013-10-14



GameView40


The Game View is rendered from the Camera(s) in your game. It is representative of your final, published game. You will need to use one or more Cameras to control what the player actually sees when they are playing your game. For more information about Cameras, please view the Camera Component page.

Play Mode

Use the buttons in the Toolbar to control the Editor Play Mode and see how your published game will play. While in Play mode, any changes you make are temporary, and will be reset when you exit Play mode. The Editor UI will darken to remind you of this.

Game View Control Bar

The first drop-down on the Game View control bar is the Aspect Drop-down. Here, you can force the aspect ratio of the Game View window to different values. It can be used to test how your game will look on monitors with different aspect ratios.

Further to the right is the Maximize on Play toggle. While enabled, the Game View will maximize itself to 100% of your Editor Window for a nice full-screen preview when you enter Play mode.

Continuing to the right is the Stats button. This shows Rendering Statistics window that is very useful for monitoring the graphics performance of your game (see Optimizing Graphics Performance for further details).

The last button is the Gizmos toggle. While enabled, all Gizmos that appear in Scene View will also be drawn in Game View. This includes Gizmos drawn using any of the Gizmos class functions. The Gizmos button also has a popup menu showing the various different types of Components used in the game.

Next to each Component's name are the settings for the icon and gizmos associated with it. The Icon setting reveals another popup menu which lets you choose from a selection of preset icons or a custom icon defined by a texture.

The Gizmo setting enables you to selectively disable Gizmo drawing for specific components.

The 3D Gizmos setting at the top of the menu refers to the Gizmo icons. With the setting enabled, the icons will show the perspective of the camera (ie, icons for nearby objects will be larger than those for distant objects), otherwise they will be the same size regardless of distance. The slider next to the checkbox allows you to vary the size of the icons, which can be useful for reducing clutter when there are a lot of gizmos visible.

Page last updated: 2012-10-19



Inspector


Games in Unity are made up of multiple GameObjects that contain meshes, scripts, sounds, or other graphical elements like Lights. The Inspector displays detailed information about your currently selected GameObject, including all attached Components and their properties. Here, you modify the functionality of GameObjects in your scene. You can read more about the GameObject-Component relationship, as it is very important to understand.

Any property that is displayed in the Inspector can be directly modified. Even script variables can be changed without modifying the script itself. You can use the Inspector to change variables at runtime to experiment and find the magic gameplay for your game. In a script, if you define a public variable of an object type (like GameObject or Transform), you can drag and drop a GameObject or Prefab into the Inspector to make the assignment.

Click the question mark beside any Component name in the Inspector to load its Component Reference page.


Add Components from the Component menu

You can click the tiny gear icon (or right-click the Component name) to bring up a context menu for the specific Component.

The Inspector will also show any Import Settings for a selected asset file.


Click Apply to reimport your asset.

Use the Layer drop-down to assign a rendering Layer to the GameObject. Use the Tag drop-down to assign a Tag to this GameObject.

Prefabs

If you have a Prefab selected, some additional buttons will be available in the Inspector. For more information about Prefabs, please view the Prefab manual page.

Icons

The inspector for all items in Unity is shown with a distinctive icon in the top left corner next to the name. For a GameObject or Prefab, a custom icon can be set to identify the object in the scene. If you click on the icon, a selection menu will appear:-

The large oblong icons at the top of the menu will show the object's name in the Scene View on a panel of the chosen color.

The smaller icons in the lower part of the menu will not show the object's name but simply identify it with a small pip of the chosen shape and color. The Other button at the bottom of the menu lets you select any texture from the project to identify the object.

Labels

Unity allows assets to be marked with Labels to make them easier to locate and categorise. The bottom item on the inspector is the Asset Labels panel.

At the bottom right of this panel is a button titled with an ellipsis ("...") character. Clicking this button will bring up a menu of available labels

You can select one or more items from the labels menu to mark the asset with those labels (they will also appear in the Labels panel). If you click a second time on one of the active labels, it will be removed from the asset.

The menu also has a text box that you can use to specify a search filter for the labels in the menu. If you type a label name that does not yet exist and press return/enter, the new label will be added to the list and applied to the selected asset. If you remove a custom label from all assets in the project, it will disappear from the list.

Once you have applied labels to your assets, you can use them to refine searches in the Project Browser (see this page for further details). You can also access an asset's labels from an editor script using the AssetDatabase class.

Page last updated: 2013-09-25



Other Views

The Views described on this page covers the basics of the interface in Unity. The other Views in Unity are described elsewhere on separate pages:

Page last updated: 2012-11-26



Customizing Your Workspace

Customizing Your Workspace

You can customize your Layout of Views by click-dragging the Tab of any View to one of several locations. Dropping a Tab in the Tab Area of an existing window will add the Tab beside any existing Tabs. Alternatively, dropping a Tab in any Dock Zone will add the View in a new window.


Views can be docked to the sides or bottom of any existing window

Tabs can also be detached from the Main Editor Window and arranged into their own floating Editor Windows. Floating Windows can contain arrangements of Views and Tabs just like the Main Editor Window.


Floating Editor Windows are the same as the Main Editor Window, except there is no Toolbar

When you've created a Layout of Editor Windows, you can Save the layout and restore it any time. You do this by expanding the Layout drop-down (found on the Toolbar) and choosing Save Layout.... Name your new layout and save it, then restore it by simply choosing it from the Layout drop-down.


A completely custom Layout

At any time, you can right-click the tab of any view to view additional options like Maximize or add a new tab to the same window.

Page last updated: 2010-09-07



Asset Workflow

Here we'll explain the steps to use a single asset with Unity. These steps are general and are meant only as an overview for basic actions. For the example, we'll talk about using a 3D mesh.

Create Rough Asset

Use any supported 3D modeling package to create a rough version of your asset. Our example will use Maya. Work with the asset until you are ready to save. For a list of applications that are supported by Unity, please see this page.

Import

When you save your asset initially, you should save it normally to the Assets folder in your Project folder. When you open the Unity project, the asset will be detected and imported into the project. When you look in the Project View, you'll see the asset located there, right where you saved it. Please note that Unity uses the FBX exporter provided by your modeling package to convert your models to the FBX file format. You will need to have the FBX exporter of your modeling package available for Unity to use. Alternatively, you can directly export as FBX from your application and save in the Projects folder. For a list of applications that are supported by Unity, please see this page.

Import Settings

If you select the asset in the Project View the import settings for this asset will appear in the Inspector. The options that are displayed will change based on the type of asset that is selected.

Adding Asset to the Scene

Simply click and drag the mesh from the Project View to the Hierarchy or Scene View to add it to the Scene. When you drag a mesh to the scene, you are creating a GameObject that has a Mesh Renderer Component. If you are working with a texture or a sound file, you will have to add it to a GameObject that already exists in the Scene or Project.

Putting Different Assets Together

Here is a brief description of the relationships between the most common assets

Creating a Prefab

Prefabs are a collection of GameObjects & Components that can be re-used in your scenes. Several identical objects can be created from a single Prefab, called instancing. Take trees for example. Creating a tree Prefab will allow you to instance several identical trees and place them in your scene. Because the trees are all linked to the Prefab, any changes that are made to the Prefab will automatically be applied to all tree instances. So if you want to change the mesh, material, or anything else, you just make the change once in the Prefab and all the other trees inherit the change. You can also make changes to an instance, and choose GameObject->Apply Changes to Prefab from the main menu. This can save you lots of time during setup and updating of assets.

When you have a GameObject that contains multiple Components and a hierarchy of child GameObjects, you can make a Prefab of the top-level GameObject (or root), and re-use the entire collection of GameObjects.

Think of a Prefab as a blueprint for a structure of GameObjects. All the Prefab clones are identical to the blueprint. Therefore, if the blueprint is updated, so are all the clones. There are different ways you can update the Prefab itself by changing one of its clones and applying those changes to the blueprint. To read more about using and updating Prefabs, please view the Prefabs page.

To actually create a Prefab from a GameObject in your scene, simply drag the GameObject from the scene into the project, and you should see the Game Object's name text turn blue. Name the new Prefab whatever you like. You have now created a re-usable prefab.

Updating Assets

You have imported, instantiated, and linked your asset to a Prefab. Now when you want to edit your source asset, just double-click it from the Project View. The appropriate application will launch, and you can make any changes you want. When you're done updating it, just Save it. Then, when you switch back to Unity, the update will be detected, and the asset will be re-imported. The asset's link to the Prefab will also be maintained. So the effect you will see is that your Prefab will update. That's all you have to know to update assets. Just open it and save!

Optional - Adding Labels to the Assets.

Is always a good idea to add labels to your assets if you want to keep organized all your assets, with this you can search for the labels associated to each asset in the search field in the project view or in the object selector.

Steps for adding a label to an asset:

Notes:

Page last updated: 2013-07-16



Creating Scenes

Scenes contain the objects of your game. They can be used to create a main menu, individual levels, and anything else. Think of each unique Scene file as a unique level. In each Scene, you will place your environments, obstacles, and decorations, essentially designing and building your game in pieces.

Instancing Prefabs

Use the method described in the last section to create a Prefab. You can also read more details about Prefabs here. Once you've created a Prefab, you can quickly and easily make copies of the Prefab, called an Instance. To create an instance of any Prefab, drag the Prefab from the Project View to the Hierarchy or Scene View. Now you have a unique instance of your Prefab to position and tweak as you like.

Adding Component & Scripts

When you have a Prefab or any GameObject highlighted, you can add additional functionality to it by using Components. Scripts are a type of Component. To add a Component, just highlight your GameObject and select a Component from the Component menu. You will then see the Component appear in the Inspector of the GameObject. Scripts are also contained in the Component menu by default.

If adding a Component breaks the GameObject's connection to its Prefab, you can always use GameObject->Apply Changes to Prefab from the menu to re-establish the link.

Placing GameObjects

Once your GameObject is in the scene, you can use the Transform Tools to position it wherever you like. Additionally, you can use the Transform values in the Inspector to fine-tune placement and rotation. Please view the Transform Component page for more information about positioning and rotating GameObjects.

Working with Cameras

Cameras are the eyes of your game. Everything the player will see while playing is through one or more cameras. You can position, rotate, and parent cameras just like any other GameObject. A camera is just a GameObject with a Camera Component attached to it. Therefore it can do anything a regular GameObject can do, and then some camera-specific functions too. There are also some helpful Camera scripts that are installed with the Scripts package. The Scripts package can be included when you create a new project, or you can use the Assets->Import Package... menu. The scripts that you import can be found in Components->Camera-Control from the menu. There are some additional aspects to cameras which will be good to understand. To read about cameras, view the Camera component page.

Lights

Except for some very few cases, you will always need to add Lights to your scene. There are three different types of lights, and all of them behave a little differently from each other. The important thing is that they add atmosphere and ambience to your game. Different lighting can completely change the mood of your game, and using lights effectively will be an important subject to learn. To read about the different lights, please view the Light component page.

Page last updated: 2013-07-31



Publishing Builds

At any time while you are creating your game, you might want to see how it looks when you build and run it outside of the editor as a standalone or web player. This section will explain how to access the Build Settings and how to create different builds of your games.

File->Build Settings... is the menu item to access the Build Settings window. It pops up an editable list of the scenes that will be included when you build your game.


The Build Settings window

The first time you view this window in a project, it will appear blank. If you build your game while this list is blank, only the currently open scene will be included in the build. If you want to quickly build a test player with only one scene file, just build a player with a blank scene list.

It is easy to add scene files to the list for multi-scene builds. There are two ways to add them. The first way is to click the Add Current button. You will see the currently open scene appear in the list. The second way to add scene files is to drag them from the Project View to the list.

At this point, notice that each of your scenes has a different index value. Scene 0 is the first scene that will be loaded when you build the game. When you want to load a new scene, use Application.LoadLevel() inside your scripts.

If you've added more than one scene file and want to rearrange them, simply click and drag the scenes on the list above or below others until you have them in the desired order.

If you want to remove a scene from the list, click to highlight the scene and press Command-Delete. The scene will disappear from the list and will not be included in the build.

When you are ready to publish your build, select a Platform and make sure that the Unity logo is next to the platform; if its not then click in the Switch Platform button to let Unity know which platform you want to build for. Finally press the Build button. You will be able to select a name and location for the game using a standard Save dialog. When you click Save, Unity builds your game pronto. It's that simple. If you are unsure where to save your built game to, consider saving it into the projects root folder. You cannot save the build into the Assets folder.

Enabling the Development Build checkbox on a player will enable Profiler functionality and also make the Autoconnect Profiler and Script Debugging options available.

Desktop

Web Player Streaming

Streaming Web Players allow your Web Player games to begin playing as soon as Scene 0 is finished loading. If you have a game with 10 levels, it doesn't make much sense to force the player to wait and download all assets for levels 2-10 before they can start playing level 1. When you publish a Streaming Web Player, the assets that must be downloaded will be sequenced in the order of the Scene file they appear in. As soon as all assets contained in Scene 0 are finished downloading, the Web Player will begin playing.

Put simply, Streaming Web Players will get players playing your game faster than ever.

The only thing you need to worry about is checking to make sure that the next level you want to load is finished streaming before you load it.

Normally, in a non-streamed player, you use the following code to load a level:

Application.LoadLevel("levelName");

In a Streaming Web Player, you must first check that the level is finished streaming. This is done through the CanStreamedLevelBeLoaded() function. This is how it works:

var levelToLoad = 1;

function LoadNewLevel () {
	if (Application.CanStreamedLevelBeLoaded (levelToLoad)) {
		Application.LoadLevel (levelToLoad);
	}
}

If you would like to display the level streaming progress to the player, for a loading bar or other representation, you can read the progress by accessing GetStreamProgressForLevel().

Offline webplayer deployment

If the Offline Deployment option is enabled for a webplayer then the UnityObject.js file (used to interface the player with the host page) will be placed alongside the player during the build. This enables the player to work with the local script file even when there is no network connection; normally, UnityObject.js is downloaded from Unity's webserver so as to make use of the latest version.

Building standalone players

With Unity you can build standalone applications for Windows and Mac (Intel, PowerPC or Universal, which runs on both architectures). It's simply a matter of choosing the build target in the build settings dialog, and hitting the 'Build' button. When building standalone players, the resulting files will vary depending on the build target. On Windows an executable file (.exe) will be built, along with a Data folder which contains all the resources for your application. On Mac an app bundle will be built, containing the file needed to run the application, as well as the resources.

Distributing your standalone on Mac is just to provide the app bundle (everything is packed in there). On Windows you need to provide both the .exe file and the Data folder for others to run it. Think of it like this: Other people must have the same files on their computer, as the resulting files that Unity builds for you, in order to run your game.

Inside the build process

The building process will place a blank copy of the built game application wherever you specify. Then it will work through the scene list in the build settings, open them in the editor one at a time, optimize them, and integrate them into the application package. It will also calculate all the assets that are required by the included scenes and store that data in a separate file within the application package.

  • Any GameObject in a scene that is tagged with 'EditorOnly' will be not be included in the published build. This is useful for debugging scripts that don't need to be included in the final game.
  • When a new level loads, all the objects in the previous level are destroyed. To prevent this, use DontDestroyOnLoad() on any objects you don't want destroyed. This is most commonly used for keeping music playing while loading a level, or for game controller scripts which keep game state and progress.
  • After the loading of a new level is finished, the message: OnLevelWasLoaded() will be sent to all active game objects.
  • For more information on how to best create a game with multiple scenes, for instance a main menu, a high-score screen, and actual game levels, see the Scripting Tutorial.pdf

iOS

Inside the iOS build process

The iPhone/iPad application build process is a two step process:

  1. XCode project is generated with all the required libraries, precompiled .NET code and serialized assets.
  2. XCode project is built and deployed on the actual device.

When "Build" is hit on "Build settings" dialog only the first step is accomplished. Hitting "Build and Run" performs both steps. If in the project save dialog the user selects an already existing folder an alert is displayed. Currently there are two XCode project generation modes to select:

  • replace - all the files from target folder are removed and the new content is generated
  • append - the "Data", "Libraries" and project root folder are cleaned and filled with newly generated content. The XCode project file is updated according to the latest Unity project changes. XCode project "Classes" subfolder could be considered as safe place to place custom native code, but making regular backups is recommended. Append mode is supported only for the existing XCode projects generated with the same Unity iOS version.

If Cmd+B is hit then the automatic build and run process is invoked and the latest used folder is assumed as the build target. In this case append mode is assumed as default.

Android

The Android application build process is performed in two steps:

  1. Application package (.apk file) is generated with all the required libraries and serialized assets.
  2. Application package is deployed on the actual device.

When "Build" is hit on "Build settings" dialog only the first step is accomplished. Hitting "Build and Run" performs both steps. If Cmd+B is hit then the automatic build and run process is invoked and the latest used file is assumed as the build target.

Upon the first attempt to build an Android project, Unity would ask you to locate the Android SDK, that is required to build and install your Android application on the device. You can change this setting later in Preferences.

When building the app to the Android, be sure that the device has the "USB Debugging" and the "Allow mock locations" checkboxes checked in the device settings.

You can ensure that the operating system sees your device by running adb devices command found in your Android SDK/platform-tools folder. This should work both for Mac and Windows.

Unity builds an application archive (.apk file) for you and installs it on the connected device. In some cases your application cannot autostart like on iPhone, so you need to unlock the screen, and in some rare cases find the newly installed application in the menu.

Texture Compression

Under Build Settings you'll also find the Texture Compression option. By default, Unity uses ETC1/RGBA16 texture format for textures that don't have individual texture format overrides (see Texture 2D / Per-Platform Overrides).

If you want to build an application archive (.apk file) targeting a specific hardware architecture, you can use the Texture Compression option to override this default behavior. Any texture that is set to not be compressed will be left alone; only textures using a compressed texture format will use the format selected in the Texture Compression option.

To make sure the application is only deployed on devices which support the selected texture compression, Unity will edit the AndroidManifest to include tags matching the particular format selected. This will enable the Android Market filtering mechanism to only serve the application to devices with the appropriate graphics hardware.

Preloading

Published builds automatically preload all assets in a scene when the scene loads. The exception to this rule is scene 0. This is because the first scene is usually a splashscreen, which you want to display as quickly as possible.

To make sure all your content is preloaded, you can create an empty scene which calls Application.LoadLevel(1). In the build settings make this empty scene's index 0. All subsequent levels will be preloaded.

You're ready to build games

By now, you have learned how to use Unity's interface, how to use assets, how to create scenes, and how to publish your builds. There is nothing stopping you from creating the game of your dreams. You'll certainly learn much more along the way, and we're here to help.

To learn more details about using Unity itself continue reading the manual.

To learn more about Scripting, please read the Scripting Reference.

To learn more about creating Art assets, please read the Assets section of the manual.

To interact with the community of Unity users and developers, visit the Unity Forums. You can ask questions, share projects, build a team, anything you want to do. Definitely visit the forums at least once, because we want to see the amazing games that you make.

Page last updated: 2013-08-12



Unity Hotkeys

This page gives an overview of the default Unity Hotkeys. You can also download a PDF of the table for Windows and MacOSX. Where a command has CTRL/CMD as part of the keystroke, this indicates that the Control key should be used on Windows and the Command key on MacOSX.

Tools
KeystrokeCommand
QPan
WMove
ERotate
RScale
ZPivot Mode toggle
XPivot Rotation Toggle
VVertex Snap
CTRL/CMD+LMBSnap
 
GameObject
CTRL/CMD+SHIFT+NNew game object
CTRL/CMD+ALT+FMove to view
CTRL/CMD+SHIFT+FAlign with view
SHIFT+F or double-FLocks the scene view camera to the selected GameObject
 
Window
CTRL/CMD+1Scene
CTRL/CMD+2Game
CTRL/CMD+3Inspector
CTRL/CMD+4Hierarchy
CTRL/CMD+5Project
CTRL/CMD+6Animation
CTRL/CMD+7Profiler
CTRL/CMD+9Asset store
CTRL/CMD+0Animation
CTRL/CMD+SHIFT+CConsole
 
Edit
CTRL/CMD+ZUndo
CTRL+Y (Windows only)Redo
CMD+SHIFT+Z (Mac only)Redo
CTRL/CMD+XCut
CTRL/CMD+CCopy
CTRL/CMD+VPaste
CTRL/CMD+DDuplicate
SHIFT+DelDelete
FFrame (centre) selection
CTRL/CMD+FFind
CTRL/CMD+ASelect All
CTRL/CMD+PPlay
CTRL/CMD+SHIFT+PPause
CTRL/CMD+ALT+PStep
 
Selection
CTRL/CMD+SHIFT+1Load Selection 1
CTRL/CMD+SHIFT+2Load Selection 2
CTRL/CMD+SHIFT+3Load Selection 3
CTRL/CMD+SHIFT+4Load Selection 4
CTRL/CMD+SHIFT+5Load Selection 5
CTRL/CMD+SHIFT+6Load Selection 6
CTRL/CMD+SHIFT+7Load Selection 7
CTRL/CMD+SHIFT+8Load Selection 8
CTRL/CMD+SHIFT+9Load Selection 9
CTRL/CMD+ALT+1Save Selection 1
CTRL/CMD+ALT+2Save Selection 2
CTRL/CMD+ALT+3Save Selection 3
CTRL/CMD+ALT+4Save Selection 4
CTRL/CMD+ALT+5Save Selection 5
CTRL/CMD+ALT+6Save Selection 6
CTRL/CMD+ALT+7Save Selection 7
CTRL/CMD+ALT+8Save Selection 8
CTRL/CMD+ALT+9Save Selection 9
 
Assets
CTRL/CMD+RRefresh

Page last updated: 2013-10-09



Preferences

Unity provides a number of preference panels to allow you to customise the behaviour of the editor.

General

Auto RefreshShould the editor update assets automatically as they change?
Always Show Project WizardShould the project wizard be shown at startup? (By default, it is shown only when the alt key is held down during launch)
Compress Assets On ImportShould assets be compressed automatically during import?
OSX Color PickerShould the native OSX color picker be used instead of Unity's own?
Editor AnalyticsCan the editor send information back to Unity automatically?
Show Asset Store search hitsShould the number of free/paid assets from the store be shown in the Project Browser?
Verify Saving AssetsShould Unity verify which assets to save individually on quitting?
Skin (Pro Only)Which color scheme should Unity use for the editor? Pro users have the option of dark grey in addition to the default light grey.

External Tools

External Script EditorWhich application should Unity use to open script files?
External Script Editor ArgsWindows only. What arguments to pass to external script editor. $(File) will be replaced with a path to a file being opened. $(Line) will be replaced with a line number that editor should jump to. See examples bellow.
Editor AttachingShould Unity allow debugging to be controlled from the external script editor?
Image ApplicationWhich application should Unity use to open image files?
Asset Server Diff ToolWhich application should Unity use to resolve file differences with the asset server?
Android SDK LocationWhere in the filesystem is the Android SDK folder located?
iOS Xcode 4.x supportShould support for Xcode 4.x be enabled for iOS build targets?

Examples for script editor args:

Gvim/Vim
--remote-tab-silent +$(Line) "$File"
Notepad2
-g $(Line) "$(File)"
Sublime Text 2
"$(File)":$(Line)
Notepad++
-n$(Line) "$(File)"

Colors

This panel allows you to choose the colors that Unity uses when displaying various user interface elements.

Keys

This panel allows you to set the keystrokes that activate the various commands in Unity.

Cache Server

Use Cache ServerShould the cache server be enabled?
IP AddressIP address of the cache server, if enabledFile"

Packages

ToDo

Page last updated: 2013-10-10



Building Scenes

This section will explain the core elements you will work with to build scenes for complete games.

Page last updated: 2007-11-16



GameObjects

GameObjects are the most important objects in Unity. It is very important to understand what a GameObject is, and how it can be used. This page will explain all that for you.

What are GameObjects?

Every object in your game is a GameObject. However, GameObjects don't do anything on their own. They need special properties before they can become a character, an environment, or a special effect. But every one of these objects does so many different things. If every object is a GameObject, how do we differentiate an interactive power-up object from a static room? What makes these GameObjects different from each other?

The answer to this question is that GameObjects are containers. They are empty boxes which can hold the different pieces that make up a lightmapped island or a physics-driven car. So to really understand GameObjects, you have to understand these pieces; they are called Components. Depending on what kind of object you want to create, you will add different combinations of Components to the GameObject. Think of a GameObject as an empty cooking pot, and Components as different ingredients that make up your recipe of gameplay. You can also make your own Components using Scripts.

You can read more about GameObjects, Components, and Script Components on the pages in this section:

Page last updated: 2010-09-14



The GameObject-Component Relationship

As described previously in GameObjects, a GameObject contains Components. We'll explore this relationship by discussing a GameObject and its most common Component -- the Transform Component. With any Unity Scene open, create a new GameObject (using Shift-Control-N on Windows or Shift-Command-N on Mac), select it and take a look at the Inspector.


The Inspector of an Empty GameObject

Notice that an empty GameObject still contains a Name, a Tag, and a Layer. Every GameObject also contains a Transform Component.

The Transform Component

It is impossible to create a GameObject in Unity without a Transform Component. The Transform Component is one of the most important Components, since all of the GameObject's Transform properties are enabled by its use of this Component. It defines the GameObject's position, rotation, and scale in the game world/Scene View. If a GameObject did not have a Transform Component, it would be nothing more than some information in the computer's memory. It effectively would not exist in the world.

The Transform Component also enables a concept called Parenting, which is utilized through the Unity Editor and is a critical part of working with GameObjects. To learn more about the Transform Component and Parenting, read the Transform Component Reference page.

Other Components

The Transform Component is critical to all GameObjects, so each GameObject has one. But GameObjects can contain other Components as well.


The Main Camera, added to each scene by default

Looking at the Main Camera GameObject, you can see that it contains a different collection of Components. Specifically, a Camera Component, a GUILayer, a Flare Layer, and an Audio Listener. All of these Components provide additional functionality to the GameObject. Without them, there would be nothing rendering the graphics of the game for the person playing! Rigidbodies, Colliders, Particles, and Audio are all different Components (or combinations of Components) that can be added to any given GameObject.

Page last updated: 2012-08-13



Using Components40

Components are the nuts & bolts of objects and behaviors in a game. They are the functional pieces of every GameObject. If you don't yet understand the relationship between Components and GameObjects, read the GameObjects page before going any further.

A GameObject is a container for many different Components. By default, all GameObjects automatically have a Transform Component. This is because the Transform dictates where the GameObject is located, and how it is rotated and scaled. Without a Transform Component, the GameObject wouldn't have a location in the world. Try creating an empty GameObject now as an example. Click the GameObject->Create Empty menu item. Select the new GameObject, and look at the Inspector.

Even empty GameObjects have a Transform Component

Remember that you can always use the Inspector to see which Components are attached to the selected GameObject. As Components are added and removed, the Inspector will always show you which ones are currently attached. You will use the Inspector to change all the properties of any Component (including scripts)

Adding Components

You can add Components to the selected GameObject through the Components menu. We'll try this now by adding a Rigidbody to the empty GameObject we just created. Select it and choose Component->Physics->Rigidbody from the menu. When you do, you will see the Rigidbody's properties appear in the Inspector. If you press Play while the empty GameObject is still selected, you might get a little surprise. Try it and notice how the Rigidbody has added functionality to the otherwise empty GameObject. (The y-component of the GameObject starts to decrease. This is because the physics engine in Unity is causing the GameObject to fall under gravity.)

An empty GameObject with a Rigidbody Component attached

Another option is to use the Component Browser, which can be activated with the Add Component button in the object's inspector.

The browser lets you navigate the components conveniently by category and also has a search box that you can use to locate components by name.

You can attach any number or combination of Components to a single GameObject. Some Components work best in combination with others. For example, the Rigidbody works with any Collider. The Rigidbody controls the Transform through the NVIDIA PhysX physics engine, and the Collider allows the Rigidbody to collide and interact with other Colliders.

If you want to know more about using a particular Component, you can read about any of them in the relevant Component Reference page. You can also access the reference page for a Component from Unity by clicking on the small ? on the Component's header in the Inspector.

Editing Components

One of the great aspects of Components is flexibility. When you attach a Component to a GameObject, there are different values or Properties in the Component that can be adjusted in the editor while building a game, or by scripts when running the game. There are two main types of Properties: Values and References.

Look at the image below. It is an empty GameObject with an Audio Source Component. All the values of the Audio Source in the Inspector are the default values.

This Component contains a single Reference property, and seven Value properties. Audio Clip is the Reference property. When this Audio Source begins playing, it will attempt to play the audio file that is referenced in the Audio Clip property. If no reference is made, an error will occur because there is no audio to be played. You must reference the file within the Inspector. This is as easy as dragging an audio file from the Project View onto the Reference Property or using the Object Selector.

Now a sound effect file is referenced in the Audio Clip property

Components can include references to any other type of Component, GameObjects, or Assets. You can read more about assigning references on the Assigning References page.

The remaining properties on the Audio Clip are all Value properties. These can be adjusted directly in the Inspector. The Value properties on the Audio Clip are all toggles, numeric values, drop-down fields, but value properties can also be text strings, colors, curves, and other types. You can read more about these and about editing value properties on the Editing Value Properties page.

Copying and pasting Component settings

The context menu for a Component has items for copying and pasting its settings.

The copied values can be pasted to an existing component using the Paste Component Values menu item. Alternatively, you can use Paste Component As New to create a new Component with those values.

Testing out Properties

While your game is in Play Mode, you are free to change properties in any GameObject's Inspector. For example, you might want to experiment with different heights of jumping. If you create a Jump Height property in a script, you can enter Play Mode, change the value, and press the jump button to see what happens. Then without exiting Play Mode you can change it again and see the results within seconds. When you exit Play Mode, your properties will revert to their pre-Play Mode values, so you don't lose any work. This workflow gives you incredible power to experiment, adjust, and refine your gameplay without investing a lot of time in iteration cycles. Try it out with any property in Play Mode. We think you'll be impressed.

Changing the order of Components

The order in which components are listed in the Inspector doesn't matter in most cases. However, there are some Components, such as Image Effects where the ordering is significant. The context menu has Move Up and Move Down commands to let you reorder Components as necessary.

Removing Components

If you want to remove a Component, option- or right-click on its header in the Inspector, and choose Remove Component. Or you can left-click the options icon next to the ? on the Component header. All the property values will be lost and this cannot be undone, so be completely sure you want to remove the Component before you do.

Page last updated: 2013-07-31



The Component-Script Relationship

When you create a script and and attach it to a GameObject, the script appears in the GameObject's Inspector just like a Component. This is because scripts become Components when they are saved - a script is just a specific type of Component. In technical terms, a script compiles as a type of Component, and is treated like any other Component by the Unity engine. So basically, a script is a Component that you are creating yourself. You will define its members to be exposed in the Inspector, and it will execute whatever functionality you've written.

Read more about creating and using scripts on the Scripting42 page.

Page last updated: 2013-07-31



DeactivatingGameObjects

A GameObject can be temporarily removed from the scene by marking it as inactive. This can be done using its activeSelf property from a script or with the activation checkbox in the inspector

A GameObject's activation checkbox

Effect of deactivating a parent GameObject

When a parent object is deactivated, the deactivation also overrides the activeSelf setting on all its child objects, so the whole hierarchy from the parent down is made inactive. Note that this does not change the value of the activeSelf property on the child objects, so they will return to their original state once the parent is reactivated. This means that you can't determine whether or not a child object is currently active in the scene by reading its activeSelf property. Instead, you should use the activeInHierarchy property, which takes the overriding effect of the parent into account.

This overriding behaviour was introduced in Unity 4.0. In earlier versions, there was a function called SetActiveRecursively which could be used to activate or deactivate the children of a given parent object. However, this function worked differently in that the activation setting of each child object was changed - the whole hierarchy could be switched off and on but the child objects had no way to "remember" the state they were originally in. To avoid breaking legacy code, SetActiveRecursively has been kept in the API for 4.0 but its use is not recommended and it may be removed in the future. In the unusual case where you actually want the children's activeSelf settings to be changed, you can use code like the following:-

// JavaScript
function DeactivateChildren(g: GameObject, a: boolean) {
	g.activeSelf = a;

	for (var child: Transform in g.transform) {
		DeactivateChildren(child.gameObject, a);
	}
}


// C#
void DeactivateChildren(GameObject g, bool a) {
	g.activeSelf = a;

	foreach (Transform child in g.transform) {
		DeactivateChildren(child.gameObject, a);
	}
}

Page last updated: 2012-10-05



Using The Inspector

The Inspector is used to view and edit Properties of many different types.

Games in Unity are made up of multiple GameObjects that contain meshes, scripts, sounds, or other graphical elements like Lights. When you select a GameObject in the Hierarchy or Scene View, the Inspector will show and let you modify the Properties of that GameObject and all the Components and Materials on it. The same will happen if you select a Prefab in the Project View. This way you modify the functionality of GameObjects in your game. You can read more about the GameObject-Component relationship, as it is very important to understand.


Inspector shows the properties of a GameObject and the Components and Materials on it.

When you create a script yourself, which works as a custom Component type, the member variables of that script are also exposed as Properties that can be edited directly in the Inspector when that script component has been added to a GameObject. This way script variables can be changed without modifying the script itself.

Furthermore, the Inspector is used for showing import options of assets such as textures, 3D models, and fonts when selected. Some scene and project-wide settings are also viewed in the Inspector, such as all the Settings Managers.

Any property that is displayed in the Inspector can be directly modified. There are two main types of Properties: Values and References. Values might be the color of a light, or a vector. References are links to other objects such as textures or other game objects.

Page last updated: 2013-10-10



Editing Value Properties40

Value properties do not reference anything and they can be edited right on the spot. Typical value properties are numbers, toggles, strings, and selection popups, but they can also be colors, vectors, curves, and other types.


Value properties on the inspector can be numbers, checkboxes, strings...

Many value properties have a text field and can be adjusted simply by clicking on them, entering a value using the keyboard, and pressing Enter to save the value.

Some Value Properties open up a small popup dialog that can be used to edit the value.

Color Picker

Properties of the Color type will open up the Color Picker. (On Mac OS X this color picker can be changed to the native OS color picker by enabling Use OS X Color Picker under Unity->Preferences.)

The Color Picker reference in the inspector is represented by:


Color Picker reference in the inspector.

And opens the Color Picker just by clicking on it:


Color Picker descriptions.

Use the Eyedropper Tool when you want to find a value just by putting your mouse over the color you want to grab.
RGB / HSV Selector lets you switch your values from Red, Green, Blue to Hue, Saturation and Value (Strength) of your color.
The transparency of the Color selected can be controlled by the Alpha Channel value.
Finally, the Preset Library section can be used to save preset values. See Preset Libraries.

Curve Editor

Properties of the AnimationCurve type will open up the Curve Editor. The Curve Editor lets you edit a curve or choose from one of the presets. For more information on editing curves, see the guide on Editing Curves.

The type is called AnimationCurve for legacy reasons, but it can be used to define any custom curve function. The function can then be evaluated at runtime from a script.

An AnimationCurve property is shown in the inspector as a small preview:


A preview of an AnimationCurve in the Inspector.

Clicking on it opens the Curve Editor:


The Curve Editor is for editing AnimationCurves.

Wrapping Mode Lets you select between Ping Pong, Clamp and Loop for the Control Keys in your curve.
The Presets lets you modify your curve to default outlines the curves can have.

Gradient editor

In graphics and animation, it is often useful to be able to blend one colour gradually into another, over space or time. A gradient is a visual representation of a colour progression, which simply shows the main colours (which are called stops) and all the intermediate shades between them. In Unity, gradients have their own special value editor, shown below.

The upward-pointing arrows along the bottom of the gradient bar denote the stops. You can select a stop by clicking on it; its value will be shown in the Color box which will open the standard colour picker when clicked. A new stop can be created by clicking just underneath the gradient bar. The position of any of the stops can be changed simply by clicking and dragging and a stop can be removed with ctrl/cmd + delete.

The downward-pointing arrows above the gradient bar are also stops but they correspond to the alpha (transparency) of the gradient at that point. By default, there are two stops set to 100% alpha (ie, fully opaque) but any number of stops can be added and edited in much the same way as the colour stops.

Arrays

Scripts that you write can expose native .Net arrays to the Inspector. When the Inspector encounters an array it will allow you to edit the length of the array. The length defaults to zero. When the size is set above zero the Inspector creates slots where you can enter values for the elements of the array. If your Array stores data of a type that Unity knows it will insert the appropriate value editor. For example:

var pickupColors : Color32[];

would result in an color picker editor for each element in the array.

Page last updated: 2013-07-16



Preset Libraries

Preset Libraries contain user created data and persist between sessions. They are integrated into the Color Picker, Gradient Editor and Curve Editors.

How to create a color preset:

  1. Click on a color field. E.g select Main Camera in the Hierarchy, then click on Background Color
  2. Adjust a color to your liking
  3. At the bottom you will find the Presets section
  4. Simply click the button to add the current color to the current preset library

Selecting a preset library in the project browser will show its contents in the inspector. From here "Edit.." can be clicked to modify.

Page last updated: 2013-06-06



Editing Reference Properties

Reference properties are properties that reference other objects such as GameObjects, Components, or Assets. The reference slot will show what kind of objects can be used for this reference.

The Audio Clip property slot shows that it accept references to objects of type AudioClip

Now an Audio Clip file is referenced in the Audio Clip property.

This type of referencing is very quick and powerful, especially when using scripting.

Object references can be assigned to a reference property either by drag and drop or by using the Object Picker.

Drag and Drop

You can use drag and drop simply by selecting the desired object in the Scene View, Hierarchy, or Project View and dragging it into the slot of the reference property.

If a reference property accepts a specific Component type (for example a Transform) then dragging a GameObject or a Prefab onto the reference property will work fine provided that the GameObject or Prefab contains a component of the correct type. The property will then reference the component in question, even though it was a GameObject or Prefab you dragged onto it.

If you drag an object onto a reference property, and the object is not of the correct type, or does not contain the right component, then you won't be able to assign the object to the reference property.

The Object Picker

You can click on the small target icon next to a reference slot to open the Object Picker.


References to the Object Picker from the Editor.

The Object Picker is a simple window for assigning objects in the inspector after allowing you to preview and search those available.

Although the Object Picker is really easy to use, there are a few things you should be aware of. These are described below.


Anatomy of the Object Picker.
  1. Search: When there are lots of objects in the picker, you can use the Search field to filter them. This search field can also search objects using their Labels.
  2. View Selector: Switches the base of the search between objects in the scene and assets.
  3. Preview Size: This horizontal scroll bar lets you increase/decrease the size of your preview objects in the preview window. With this you can see more or fewer objects in the preview window at any moment.
  4. Preview Window: Here are all the objects that reside in your Scene/Assets folder filtered by the Search field.
  5. Object Info: Displays information about the currently selected object. The content of this field depends on the type of object being viewed, so if for example you pick a mesh, it will tell you the number of vertices and triangles, and whether or not it has UVs and is skinned. However, if you pick an audio file it will give you information such as the bit rate of the audio, the length, etc.
  6. Object Preview: This also depends on the type of object you are viewing. If you select a mesh, it will display you how the mesh looks, but if you select a script file, it will just display an icon of the file.

The Object Picker works on any asset you have in your project, which can be a video, a song, a terrain, a GUI skin, a scripting file, or a mesh; it is a tool you will use often.

Hints

Page last updated: 2013-07-31



Multi-Object Editing

Starting in Unity 3.5 you can select multiple objects of the same type and edit them simultaneously in the Inspector. Any changed properties will be applied to all of the selected objects. This is a big time saver if you want to make the same change to many objects.

When selecting multiple objects, a component is only shown in the Inspector if that component exists on all the selected objects. If it only exists on some of them, a small note will appear at the bottom of the Inspector saying that components that are only on some of the selected objects cannot be multi-edited.

Property Values

When multiple objects are selected, each property shown in the Inspector represents that property on each of the selected objects. If the value of the property is the same for all the objects, the value will be shown as normal, just like when editing a single object. If the value of the property is not the same for all the selected objects, no value is shown and a dash or similar is shown instead, indicating that the values are different.

Multi-edit of two objects

Regardless of whether a value is shown or a dash, the property value can be edited as usual and the changed value is applied to all the selected objects. If the values are different and a dash is thus shown, it's also possible to right-click on the label of the property. This brings up a menu that lets you choose from which of the objects to inherit the value.

Selecting which object to get the value from

Multi-Editing Prefab or Model Instances

Prefabs can be multi-edited just like Game Objects in the scene. Instances of prefabs or of models can also be multi-edited; however certain restrictions apply: When editing a single prefab or model instance, any property that is different from the prefab or model will appear in bold, and when right clicking there's an option to revert the property to the value it has in the prefab or model. Furthermore, the Game Object has options to apply or revert all changes. None of these things are available when multi-object editing. Properties cannot be reverted or applied; nor will they appear in bold if different from the prefab or model. To remind you of this, the Inspector will show a note with Instance Management Disabled where the Select, Revert, and Apply buttons would normally appear.

Instance Management Disabled for multi-edit of prefabs

Non-Supported Objects

A few object types do not support multi-object editing. When you select multiple objects simultaneously, these objects will show a small note saying "Multi-object editing not supported".

If you have made a custom editor for one of your own scripts, it will also show this message if it doesn't support multi-object editing. See the script reference for the Editor class to learn how to implement support for multi-object editing for your own custom editors.

Page last updated: 2013-07-12



Inspector Options

The Inspector Lock and the Inspector Debug Mode are two useful options that can help you in your workflow.

Lock

The Lock lets you maintain focus on a specific GameObject in the Inspector while selecting other GameObjects. To toggle the lock of an Inspector click on the padlock icon at the top right of the Inspector or open the tab menu and select Lock.


Locking the Inspector from the tab menu.

Note that you can have more than one Inspector open, and that you can for example lock one of them to a specific GameObject while keeping the other one unlocked to show whichever GameObject is selected.

Debug

The Debug Mode lets you inspect private variables of components in the Inspector, which are normally not shown. To change to Debug Mode, open the tab menu and select Debug.

In Debug Mode, all components are shown using a default interface, rather than the custom interfaces that some components use in the Normal Mode. For example, the Transform component will in Debug Mode show the raw Quaternion values of the rotation rather than the Euler angles shown in the Normal Mode. You can also use the Debug Mode to inspect the values of private variables in your own script components.


Debug Mode in the Inspector lets you inspect private variables in your scripts and in other components.

The Debug mode is per Inspector and you can have one Inspector in Debug Mode while another one is not.

Page last updated: 2013-07-16



Using The Scene View43

The Scene View is your interactive sandbox. You will use the Scene View to select and position environments, the player, the camera, enemies, and all other GameObjects. Maneuvering and manipulating objects within the Scene View are some of the most important functions in Unity, so it's important to be able to do them quickly.

Page last updated: 2013-09-23



Scene View Navigation43

The Scene View has a set of navigation controls to help you move around quickly and efficiently.

Arrow Movement

You can use the Arrow Keys to move around the scene as though "walking" through it. The up and down arrows move the camera forward and backward in the direction it is facing. The left and right arrows pan the view sideways. Hold down the Shift key with an arrow to move faster.

Focusing

If you select a GameObject in the hierarchy, then move the mouse over the scene view and press the F key, the view will move so as to center on the object. This feature is referred to as frame selection.

Move, Orbit and Zoom

Moving, orbiting and zooming are key operations in Scene View navigation, so Unity provides several alternative ways to perform them for maximum convenience.

Using the Hand Tool

When the hand tool is selected (shortcut: Q), the following mouse controls are available:

Move: Click-drag to drag the camera around.
Orbit: Hold Alt and click-drag to orbit the camera around the current pivot point.
Zoom: Hold Control (Command on Mac) and click-drag to zoom the camera.

Holding down Shift will increase the rate of movement and zooming.

Shortcuts Without Using the Hand Tool

For extra efficiency, all of these controls can also be used regardless of which transform tool is selected. The most convenient controls depend on which mouse or track-pad you are using:

Action3-button mouse2-button mouse or track-padMac with only one mouse button or track-pad
MoveHold Alt and middle click-drag.Hold Alt-Control and click-drag.Hold Alt-Command and click-drag.
OrbitHold Alt and click-drag.Hold Alt and click-drag.Hold Alt and click-drag.
ZoomHold Alt and right click-drag or use scroll-wheel.Hold Alt and right click-drag.Hold Alt-Control and click-drag or use two-finger swipe.

Flythrough Mode

The Flythrough mode lets you navigate the Scene View by flying around in first person similar to how you would navigate in many games.

Flythrough mode is designed for Perspective Mode. In Isometric Mode, holding down the right mouse button and moving the mouse will orbit the camera instead.

Scene Gizmo

In the upper-right corner of the Scene View is the Scene Gizmo. This displays the Scene View Camera's current orientation, and allows you to quickly modify the viewing angle.

You can click on any of the arms to snap the Scene View Camera to that direction. Click the middle of the Scene Gizmo, or the text below it, to toggle between Isometric Mode and Perspective Mode. You can also always shift-click the middle of the Scene Gizmo to get a "nice" perspective view with an angle that is looking at the scene from the side and slightly from above.

Note that in 2D mode, the scene gizmo will not be displayed since the only option is to have the view looking perpendicularly at the XY plane.

Mac Trackpad Gestures

On a Mac with a trackpad, you can drag with two fingers to zoom the view.

You can also use three fingers to simulate the effect of clicking the arms of the Scene Gizmo: drag up, left, right or down to snap the Scene View Camera to the corresponding direction. In OS X 10.7 "Lion" you may have to change your trackpad settings in order to enable this feature:

Page last updated: 2013-09-23



Positioning GameObjects43

When building your games, you'll place lots of different objects in your game world.

Focusing

It can be useful to focus the Scene View Camera on an object before manipulating it. Select any GameObject and press the F key. This will center the Scene View and pivot point on the selection. This is also known as Frame Selection.

Translate, Rotate, and Scale

Use the Transform Tools in the Toolbar to Translate, Rotate, and Scale individual GameObjects. Each has a corresponding Gizmo that appears around the selected GameObject in the Scene View. You can use the mouse and manipulate any Gizmo axis to alter the Transform Component of the GameObject, or you can type values directly into the number fields of the Transform Component in the Inspector. Each of the three transform modes can be selected with a hotkey - W for Translate, E for Rotate and R for Scale.

You can click and drag in the center of the Gizmo to manipulate the object on all axes at once. At the center of the Translate gizmo, there are three small squares that can be used to drag the object within a single plane (ie, two axes can be moved at once while the third is kept still). If you have a three button mouse, you can click the middle button and drag to adjust the axis that was most recently moved (the arrow for this axis will change to yellow).

With the rotation tool selected, you can change the object's rotation by clicking and dragging the axes of the wireframe sphere gizmo that appears around it. As with the translation tool, the last axis you changed will be colored yellow and can be further adjusted by clicking the middle mouse button and dragging.

The scaling tool lets you rescale the object evenly on all axes at once by clicking and dragging on the cube at the center of the gizmo. You can also scale the axes individually, but you should take care if you do this when there are child objects since the effect can look quite strange. Again, the last axis changed appears in yellow and can be adjusted by dragging with the middle mouse button.

Note that in 2D mode, the Z axis can't be changed in the scene using the gizmos. However, it is useful for certain scripting techniques to use the Z axis for other purposes; you can still set the Z axis from the inspector in such cases.

For more information on transforming GameObjects, please view the Transform Component page.

Gizmo Display Toggles

The Gizmo Display Toggles are used to define the location of any Transform Gizmo.


Gizmo Display Toggles

For Position:

For Rotation:

Unit Snapping

While dragging any Gizmo Axis using the Translate Tool, you can hold the Control key (Command on Mac) to snap to increments defined in the Snap Settings.

You can change the unit distance that is used for the unit snapping using the menu Edit->Snap Settings...


Scene View Unit Snapping settings.

Surface Snapping

While dragging in the center using the Translate Tool, you can hold Shift and Control (Command on Mac) to snap the object to the intersection of any Collider. This makes precise positioning of objects incredibly fast.

Look-At Rotation

While using the Rotate Tool, you can hold Shift and Control (Command on Mac) to rotate the object towards a point on the surface of any Collider. This makes orientation of objects relative to one another simple.

Vertex Snapping

You can assemble your worlds more easily with a feature called Vertex Snapping. This feature is a really simple but powerful tool in Unity. It lets you take any vertex from a given mesh and with your mouse place that vertex in the same position as any vertex from any other mesh you choose.

With this you can assemble your worlds really fast. For example, you could align road sections precisely in a racing game or position power up items at the vertices of a mesh.

Using vertex snapping in Unity is simple. Just follow these steps:

Page last updated: 2013-09-24



View Modes43

The Scene View control bar lets you choose various options for viewing the scene and also control whether lighting and audio are enabled. These controls only affect the scene view during development and have no effect on the built game.

Draw Mode

The first drop-down menu selects which Draw Mode will be used to depict the scene. The available options are:

Render Mode

The next drop-down along selects which of four Render Modes will be used to render the scene:-

2D, Lighting and Audio Switches

To the right of the render mode menu are three buttons that switch certain scene view options on or off:-

Effects Button and Menu

The menu (activated by the small arrow to the right of the word "Effects") has options to enable or disable rendering effects in the scene view.

The Effects button itself acts as a switch that enables or disables all the effects at once.

Gizmos Menu

Gizmos are graphics added to the scene (either by Unity itself or from your own scripts) that help with visualisation and identification of items in the game world. For example, you can add icons to help identify your game objects and use simple wireframe graphics to show otherwise invisible paths and positioning elements. See the Script Reference page for the OnDrawGizmos function for further information about implementing custom gizmos in your scripts.

Clicking the Gizmos popup will show a menu with a number of options:-

The 3D Gizmos checkbox determines whether gizmos are shown in true 3D (with correct obscuration and perspective) or as a simple overlay on top of other scene graphics. The slider to its right adjusts the scale of gizmo icons relative to other objects. The Show Grid checkbox below switches the standard scene measurement grid on and off.

Beneath these options is a table of component names with Icon and Gizmo columns to the right. The list is subdivided into user scripts and built-in components and will also maintain a section of recently changed items as you make modifications.

The Icon column lets you select the gizmo icon displayed for particular component types. For built-in components, the only options are to have no icon (as with Colliders, where only a wireframe gizmo is shown) or simply to switch the standard icon on and off (as with Cameras, Lights and Audio Sources, among others). For user scripts, clicking the icon column will bring up a menu to select the desired icon:-

This lets you select from a variety of simple standard icon shapes in different colors that you can use to identify particular script types. The Other button will bring up a texture selector from which you can choose any texture you like to use as the icon for your script.

The Gizmo column in the table contains a checkbox that lets you choose whether gizmo graphics will be drawn for a particular Component type. For example, Colliders have a predefined wireframe gizmo to show their shape while user scripts can draw custom gizmos appropriate to their purpose; these gizmos can be turned on or off by clicking in this column.

Search Box

The rightmost item on the control bar is a search box that lets you filter items in the scene view by their names and/or types (you can select which with the small menu at the left of the search box). The set of items that match the search filter will also be shown in the Hierarchy view which, by default, is located to the left of the Scene view.

Page last updated: 2013-09-24



Searching

When working with large complex scenes it can be useful to search for specific objects. By using the Search feature in Unity, you can filter out only the object or group of objects that you want to see. You can search assets by their name, by Component type, and in some cases by asset Labels. You can specify the search mode by choosing from the Search drop-down menu.

Scene Search

When a scene is loaded in the Editor, you can see the objects in both the Scene View and the Hierarchy. The specific assets are shared in both places, so if you type in a search term (eg, "elevator"), you'll see the the filter applied both visually in the Scene View and a more typical manner in the Hierarchy. There is also no difference between typing the search term into the search field in the Scene View or the Hierachy -- the filter takes effect in both views in either case.


Scene View and Hierarchy with no search applied.

Scene View and Hierarchy with active filtering of search term.

When a search term filter is active, the Hierarchy doesn't show hierarchical relationships between GameObjects, but you can select any GameObject, and it's hierarchical path in the scene will be shown at the bottom of the Hierarchy.

Click on a GameObject in the filtered list to see its hierarchical path.

When you want to clear the search filter, just click the small cross in the search field.

In the Scene search you can search either by Name or by Type. Click on the small magnifying glass in the search field to open the search drop-down menu and choose the search mode.

Search by Name, Type, or All.

Project Search

The same fundamentals apply to searching of assets in the Project View -- just type in your search term and you'll see all the relevant assets appear in the filter.

In the Project search you can search by Name or by Type as in the Scene search, and additionally you can search by Label. Click on the small magnifying glass in the search field to open the search drop-down menu and choose the search mode.

Search by Name, Type, Label, or All.

Object Picker Search

When assigning an object via the Object Picker, you can also enter a search term search to filter the objects you want to see.

Page last updated: 2011-11-10



Prefabs

A Prefab is a type of asset -- a reusable GameObject stored in Project View. Prefabs can be inserted into any number of scenes, multiple times per scene. When you add a Prefab to a scene, you create an instance of it. All Prefab instances are linked to the original Prefab and are essentially clones of it. No matter how many instances exist in your project, when you make any changes to the Prefab you will see the change applied to all instances.

Creating Prefabs

In order to create a Prefab, simply drag a GameObject that you've created in the scene into the Project View. The GameObject's name will turn blue to show that it is a Prefab. You can rename your new Prefab.

After you have performed these steps, the GameObject and all its children have been copied into the Prefab data. The Prefab can now be re-used in multiple instances. The original GameObject in the Hierarchy has now become an instance of the Prefab.

Prefab Instances

To create a Prefab instance in the current scene, drag the Prefab from the Project View into the Scene or Hierarchy View. This instance is linked to the Prefab, as displayed by the blue text used for their name in the Hierarchy View.

Three of these GameObjects are linked to Prefabs. One of them is not.

Inheritance

Inheritance means that whenever the source Prefab changes, those changes are applied to all linked GameObjects. For example, if you add a new script to a Prefab, all of the linked GameObjects will instantly contain the script as well. However, it is possible to change the properties of a single instance while keeping the link intact. Simply change any property of a prefab instance, and watch as the variable name becomes bold. The variable is now overridden. All overridden properties will not be affected by changes in the source Prefab.

This allows you to modify Prefab instances to make them unique from their source Prefabs without breaking the Prefab link.


A linked GameObject with no overrides enabled.

A linked GameObject with several (bold) overrides enabled.

Imported Prefabs

When you place a mesh asset into your Assets folder, Unity automatically imports the file and generates something that looks similar to a Prefab out of the mesh. This is not actually a Prefab, it is simply the asset file itself. Instancing and working with assets introduces some limitations that are not present when working with normal Prefabs.


Notice the asset icon is a bit different from the Prefab icons

The asset is instantiated in the scene as a GameObject, linked to the source asset instead of a normal Prefab. Components can be added and removed from this GameObject as normal. However, you cannot apply any changes to the asset itself since this would add data to the asset file itself! If you're creating something you want to re-use, you should make the asset instance into a Prefab following the steps listed above under "Creating Prefabs".

Note: When you have selected an instance of an asset, the Apply button in the Inspector is replaced with an Edit button. Clicking this button will launch the editing application for your asset (e.g. Maya or Max).

Page last updated: 2013-07-16



Lights

Lights are an essential part of every scene. While meshes and textures define the shape and look of a scene, lights define the color and mood of your 3D environment. You'll likely work with more than one light in each scene. Making them work together requires a little practice but the results can be quite amazing.

A simple, two-light setup

Lights can be added to your scene from the GameObject->Create Other menu. Once a light has been added, you can manipulate it like any other GameObject. Additionally, you can add a Light Component to any selected GameObject by using Component->Rendering->Light.

There are many different options within the Light Component in the Inspector.

Light Component properties in the Inspector

By simply changing the Color of a light, you can give a whole different mood to the scene.

Bright, sunny lights

Dark, medieval lights

Spooky night lights

The lights you create this way are realtime lights - their lighting is calculated each frame while the game is running. If you know the light will not change, you can make your game faster and look much better by using Lightmapping.

Rendering paths

Unity supports different Rendering Paths. These paths affect mainly Lights and Shadows, so choosing the correct rendering path depending on your game requirements can improve your project's performance. For more info about rendering paths you can visit the Rendering paths section.

More information

For more information about using Lights, check the Lights page in the Manual.

Page last updated: 2013-10-14



Cameras

Just as cameras are used in films to display the story to the audience, Cameras in Unity are used to display the game world to the player. You will always have at least one camera in a scene, but you can have more than one. Multiple cameras can give you a two-player splitscreen or create advanced custom effects. You can animate cameras, or control them with physics. Practically anything you can imagine is possible with cameras, and you can use typical or unique cameras to fit your game's style.

The remaining text is from the Camera Component reference page.

Camera

Cameras are the devices that capture and display the world to the player. By customizing and manipulating cameras, you can make the presentation of your game truly unique. You can have an unlimited number of cameras in a scene. They can be set to render in any order, at any place on the screen, or only certain parts of the screen.


Unity's flexible Camera object

Properties

Clear FlagsDetermines which parts of the screen will be cleared. This is handy when using multiple Cameras to draw different game elements.
BackgroundColor applied to the remaining screen after all elements in view have been drawn and there is no skybox.
Culling MaskInclude or omit layers of objects to be rendered by the Camera. Assign layers to your objects in the Inspector.
ProjectionToggles the camera's capability to simulate perspective.
PerspectiveCamera will render objects with perspective intact.
OrthographicCamera will render objects uniformly, with no sense of perspective.
Size (when Orthographic is selected)The viewport size of the Camera when set to Orthographic.
Field of view (when Perspective is selected)Width of the Camera's view angle, measured in degrees along the local Y axis.
Clipping PlanesDistances from the camera to start and stop rendering.
NearThe closest point relative to the camera that drawing will occur.
FarThe furthest point relative to the camera that drawing will occur.
Normalized View Port RectFour values that indicate where on the screen this camera view will be drawn, in Screen Coordinates (values 0-1).
XThe beginning horizontal position that the camera view will be drawn.
YThe beginning vertical position that the camera view will be drawn.
W (Width)Width of the camera output on the screen.
H (Height)Height of the camera output on the screen.
DepthThe camera's position in the draw order. Cameras with a larger value will be drawn on top of cameras with a smaller value.
Rendering PathOptions for defining what rendering methods will be used by the camera.
Use Player SettingsThis camera will use whichever Rendering Path is set in the Player Settings.
Vertex LitAll objects rendered by this camera will be rendered as Vertex-Lit objects.
ForwardAll objects will be rendered with one pass per material.
Deferred Lighting (Unity Pro only)All objects will be drawn once without lighting, then lighting of all objects will be rendered together at the end of the render queue.
Target Texture (Unity Pro only)Reference to a Render Texture that will contain the output of the Camera view. Making this reference will disable this Camera's capability to render to the screen.
HDREnables High Dynamic Range rendering for this camera.

Details

Cameras are essential for displaying your game to the player. They can be customized, scripted, or parented to achieve just about any kind of effect imaginable. For a puzzle game, you might keep the Camera static for a full view of the puzzle. For a first-person shooter, you would parent the Camera to the player character, and place it at the character's eye level. For a racing game, you'd likely want to have the Camera follow your player's vehicle.

You can create multiple Cameras and assign each one to a different Depth. Cameras are drawn from low Depth to high Depth. In other words, a Camera with a Depth of 2 will be drawn on top of a Camera with a depth of 1. You can adjust the values of the Normalized View Port Rectangle property to resize and position the Camera's view onscreen. This can create multiple mini-views like missile cams, map views, rear-view mirrors, etc.

Render Path

Unity supports different Rendering Paths. You should choose which one you use depending on your game content and target platform / hardware. Different rendering paths have different features and performance characteristics that mostly affect Lights and Shadows.
The rendering Path used by your project is chosen in Player Settings. Additionally, you can override it for each Camera.

For more info on rendering paths, check the rendering paths page.

Clear Flags

Each Camera stores color and depth information when it renders its view. The portions of the screen that are not drawn in are empty, and will display the skybox by default. When you are using multiple Cameras, each one stores its own color and depth information in buffers, accumulating more data as each Camera renders. As any particular Camera in your scene renders its view, you can set the Clear Flags to clear different collections of the buffer information. This is done by choosing one of the four options:

Skybox

This is the default setting. Any empty portions of the screen will display the current Camera's skybox. If the current Camera has no skybox set, it will default to the skybox chosen in the Render Settings (found in Edit->Render Settings). It will then fall back to the Background Color. Alternatively a Skybox component can be added to the camera. If you want to create a new Skybox, you can use this guide.

Solid Color

Any empty portions of the screen will display the current Camera's Background Color.

Depth Only

If you wanted to draw a player's gun without letting it get clipped inside the environment, you would set one Camera at Depth 0 to draw the environment, and another Camera at Depth 1 to draw the weapon alone. The weapon Camera's Clear Flags should be set to to depth only. This will keep the graphical display of the environment on the screen, but discard all information about where each object exists in 3-D space. When the gun is drawn, the opaque parts will completely cover anything drawn, regardless of how close the gun is to the wall.


The gun is drawn last, after clearing the depth buffer of the cameras before it

Don't Clear

This mode does not clear either the color or the depth buffer. The result is that each frame is drawn over the next, resulting in a smear-looking effect. This isn't typically used in games, and would likely be best used with a custom shader.

Clip Planes

The Near and Far Clip Plane properties determine where the Camera's view begins and ends. The planes are laid out perpendicular to the Camera's direction and are measured from the its position. The Near plane is the closest location that will be rendered, and the Far plane is the furthest.

The clipping planes also determine how depth buffer precision is distributed over the scene. In general, to get better precision you should move the Near plane as far as possible.

Note that the near and far clip planes together with the planes defined by the field of view of the camera describe what is popularly known as the camera frustum. Unity ensures that when rendering your objects those which are completely outside of this frustum are not displayed. This is called Frustum Culling. Frustum Culling happens irrespective of whether you use Occlusion Culling in your game.

For performance reasons, you might want to cull small objects earlier. For example, small rocks and debris could be made invisible at much smaller distance than large buildings. To do that, put small objects into a separate layer and setup per-layer cull distances using Camera.layerCullDistances script function.

Culling Mask

The Culling Mask is used for selectively rendering groups of objects using Layers. More information on using layers can be found here.

Commonly, it is good practice to put your User Interface on a different layer, then render it by itself with a separate Camera set to render the UI layer by itself.

In order for the UI to display on top of the other Camera views, you'll also need to set the Clear Flags to Depth only and make sure that the UI Camera's Depth is higher than the other Cameras.

Normalized Viewport Rectangle

Normalized Viewport Rectangles are specifically for defining a certain portion of the screen that the current camera view will be drawn upon. You can put a map view in the lower-right hand corner of the screen, or a missile-tip view in the upper-left corner. With a bit of design work, you can use Viewport Rectangle to create some unique behaviors.

It's easy to create a two-player split screen effect using Normalized Viewport Rectangle. After you have created your two cameras, change both camera H value to be 0.5 then set player one's Y value to 0.5, and player two's Y value to 0. This will make player one's camera display from halfway up the screen to the top, and player two's camera will start at the bottom and stop halfway up the screen.


Two-player display created with the Normalized Viewport Rectangle property

Orthographic

Marking a Camera as Orthographic removes all perspective from the Camera's view. This is mostly useful for making isometric or 2D games.

Note that fog is rendered uniformly in orthographic camera mode and may therefore not appear as expected. Read more about why in the component reference on Render Settings.


Perspective camera.

Orthographic camera. Objects do not get smaller with distance here!

Render Texture

This feature is only available for Unity Advanced licenses . It will place the camera's view onto a Texture that can then be applied to another object. This makes it easy to create sports arena video monitors, surveillance cameras, reflections etc.


A Render Texture used to create a live arena-cam

Hints

Page last updated: 2007-11-16



Terrains

This section will explain how to use the Terrain Engine. It will cover creation, technical details, and other considerations. It is broken into the following sections:

Using Terrains

This section covers the most basic information about using Terrains. This includes creating Terrains and how to use the new Terrain tools & brushes.

Height

This section explains how to use the different tools and brushes that alter the Height of the Terrain.

Terrain Textures

This section explains how to add, paint and blend Terrain Textures using different brushes.

Trees

This section contains important information for creating your own tree assets. It also covers adding and painting trees on your Terrain.

Grass

This section explains how grass works, and how to use it.

Detail Meshes

This section explains practical usage for detail meshes like rocks, haystacks, vegetation, etc.

Lightmaps

You can lightmap terrains just like any other objects using Unity's built-in lightmapper. See Lightmapping Quickstart for help.

Other Settings

This section covers all the other settings associated with Terrains.

Mobile performance note

Rendering terrain is quite expensive, so terrain engine is not very practical on lower-end mobile devices.

Page last updated: 2010-06-03



Asset Import and Creation

A large part of making a game is utilizing your asset source files in your GameObjects. This goes for textures, models, sound effects and behaviour scripts. Using the Project View inside Unity, you have quick access to all the files that make up your game:


The Project View displays all source files and created Prefabs

This view shows the organization of files in your project's Assets folder. Whenever you update one of your asset files, the changes are immediately reflected in your game!

To import an asset file into your project, move the file into (your Project folder)->Assets in the Finder, and it will automatically be imported into Unity. To apply your assets, simply drag the asset file from the Project View window into the Hierarchy or Scene View. If the asset is meant to be applied to another object, drag the asset over the object.

Hints

Continue reading for more information:

Page last updated: 2013-07-16



PrimitiveObjects

Unity can work with 3D models of any shape that can be created with modelling software. However, there are also a number of primitive object types that can be created directly within Unity, namely the Cube, Sphere, Capsule, Cylinder, Plane and Quad. These objects are often useful in their own right (a plane is commonly used as a flat ground surface, for example) but they also offer a quick way to create placeholders and prototypes for testing purposes. Any of the primitives can be added to the scene using the appropriate item on the GameObject > Create Other menu.

Cube

This is a simple cube with sides one unit long, textured so that the image is repeated on each of the six faces. As it stands, a cube isn't really a very common object in most games but when scaled, it is very useful for walls, posts, boxes, steps and other similar items. It is also a handy placeholder object for programmers to use during development when a finished model is not yet available. For example, a car body can be crudely modelled using an elongated box of roughly the right dimensions. Although this is not suitable for the finished game, it is fine as a simple representative object for testing the car's control code. Since a cube's edges are one unit in length, you can check the proportions of a mesh imported into the scene by adding a cube close by and comparing the sizes.

Sphere

This is a sphere of unit diameter (ie, 0.5 unit radius), textured so that the entire image wraps around once with the top and bottom "pinched" at the poles. Spheres are obviously useful for representing balls, planets and projectiles but a semi-transparent sphere can also make a nice GUI device for representing the radius of an effect.

Capsule

A capsule is a cylinder with hemispherical caps at the ends. The object is one unit in diameter and two units high (the body is one unit and the two caps are half a unit each). It is textured so that the image wraps around exactly once, pinched at each hemisphere's apex. While there aren't many real world objects with this shape, the capsule is a useful placeholder for prototyping. In particular, the physics of a rounded object are sometimes better than those of a box for certain tasks.

Cylinder

This is a simple cylinder which is two units high and one unit in diameter, textured so that the image wraps once around the tube shape of the body but also appears separately in the two flat, circular ends. Cylinders are very handy for creating posts, rods and wheels but you should note that the shape of the collider is actually a capsule (there is no primitive cylinder collider in Unity). You should create a mesh of the appropriate shape in a modelling program and attach a mesh collider if you need an accurate cylindrical collider for physics purposes.

Plane

This is a flat square with edges ten units long oriented in the XZ plane of the local coordinate space. It is textured so that the whole image appears exactly once within the square. A plane is useful for most kinds of flat surface, such as floors and walls. A surface is also needed sometimes for showing images or movies in GUI and special effects. Although a plane can be used for things like this, the simpler quad primitive is often a more natural fit to the task.

Quad

The quad primitive resembles the plane but its edges are only one unit long and the surface is oriented in the XY plane of the local coordinate space. Also, a quad is divided into just two triangles whereas the plane contains two hundred. A quad is useful in cases where a scene object must be used simply as a display screen for an image or movie. Simple GUI and information displays can be implemented with quads, as can particles, sprites and "impostor" images that substitute for solid objects viewed at a distance.

Page last updated: 2013-04-22



Importing Assets

Unity will automatically detect files as they are added to your Project folder's Assets folder. When you put any asset into your Assets folder, you will see the asset appear in your Project View.


The Project View is your window into the Assets folder, normally accessible from the file manager

When you are organizing your Project View, there is one very important thing to remember:

Never move any assets or organize this folder from the Explorer (Windows) or Finder (OS X). Always use the Project View

There is a lot of meta data stored about relationships between asset files within Unity. This data is all dependent on where Unity expects to find these assets. If you move an asset from within the Project View, these relationships are maintained. If you move them outside of Unity, these relationships are broken. You'll then have to manually re-link lots of dependencies, which is something you probably don't want to do.

So just remember to only save assets to the Assets folder from other applications, and never rename or move files outside of Unity. Always use Project View. You can safely open files for editing from anywhere, of course.

Creating and Updating Assets

When you are building a game and you want to add a new asset of any type, all you have to do is create the asset and save it somewhere in the Assets folder. When you return to Unity or launch it, the added file(s) will be detected and imported.

Additionally, as you update and save your assets, the changes will be detected and the asset will be re-imported in Unity. This allows you to focus on refining your assets without struggling to make them compatible with Unity. Updating and saving your assets normally from its native application provides optimum, hassle-free workflow that feels natural.

Default Values

On some importers it is possible to specify default values for the field references or similar. To specify a default value open the object selector on the field you wish to set a default value for and select an value from the object selector.

Asset Types

There are a handful of basic asset types that will go into your game. The types are:

We'll discuss the details of importing each of these file types and how they are used.

Meshes & Animations

Whichever 3D package you are using, Unity will import the meshes and animations from each file. For a list of applications that are supported by Unity, please see this page.

Your mesh file does not need to have an animation to be imported. If you do use animations, you have your choice of importing all animations from a single file, or importing separate files, each with one animation. For more information about importing animations, please see the Legacy animation system page.

Once your mesh is imported into Unity, you can drag it to the Scene or Hierarchy to create an instance of it. You can also add Components to the instance, which will not be attached to mesh file itself.

Meshes will be imported with UVs and a number of default Materials (one material per UV). You can then assign the appropriate texture files to the materials and complete the look of your mesh in Unity's game engine.

Textures

Unity supports all image formats. Even when working with layered Photoshop files, they are imported without disturbing the Photoshop format. This allows you to work with a single texture file for a very care-free and streamlined experience.

You should make your textures in dimensions that are to the power of two (e.g. 32x32, 64x64, 128x128, 256x256, etc.) Simply placing them in your project's Assets folder is sufficient, and they will appear in the Project View.

Once your texture has been imported, you should assign it to a Material. The material can then be applied to a mesh, Particle System, or GUI Texture. Using the Import Settings, it can also be converted to a Cubemap or Normalmap for different types of applications in the game. For more information about importing textures, please read the Texture Component page.

Sounds

Desktop

Unity features support for two types of audio: Uncompressed Audio or Ogg Vorbis. Any type of audio file you import into your project will be converted to one of these formats.

File Type Conversion

.AIFFConverted to uncompressed audio on import, best for short sound effects.
.WAVConverted to uncompressed audio on import, best for short sound effects.
.MP3Converted to Ogg Vorbis on import, best for longer music tracks.
.OGGCompressed audio format, best for longer music tracks.

Import Settings

If you are importing a file that is not already compressed as Ogg Vorbis, you have a number of options in the Import Settings of the Audio Clip. Select the Audio Clip in the Project View and edit the options in the Audio Importer section of the Inspector. Here, you can compress the Clip into Ogg Vorbis format, force it into Mono or Stereo playback, and tweak other options. There are positives and negatives for both Ogg Vorbis and uncompressed audio. Each has its own ideal usage scenarios, and you generally should not use either one exclusively.

Read more about using Ogg Vorbis or Uncompressed audio on the Audio Clip Component Reference page.

iOS

Unity features support for two types of audio: Uncompressed Audio or MP3 Compressed audio. Any type of audio file you import into your project will be converted to one of these formats.

File Type Conversion

.AIFFImports as uncompressed audio for short sound effects. Can be compressed in Editor on demand.
.WAVImports as uncompressed audio for short sound effects. Can be compressed in Editor on demand.
.MP3Imports as Apple Native compressed format for longer music tracks. Can be played on device hardware.
.OGGOGG compressed audio format, incompatible with the iPhone device. Please use MP3 compressed sounds on the iPhone.

Import Settings

When you are importing an audio file, you can select its final format and choose to force it to stereo or mono channels. To access the Import Settings, select the Audio Clip in the Project View and find the Audio Importer in the Inspector. Here, you can compress the Clip into Ogg Vorbis format, force it into Mono or Stereo playback, and tweak other options, such as the very important Decompress On Load setting.

Read more about using MP3 Compressed or Uncompressed audio on the Audio Clip Component Reference page.

Android

Unity features support for two types of audio: Uncompressed Audio or MP3 Compressed audio. Any type of audio file you import into your project will be converted to one of these formats.

File Type Conversion

.AIFFImports as uncompressed audio for short sound effects. Can be compressed in Editor on demand.
.WAVImports as uncompressed audio for short sound effects. Can be compressed in Editor on demand.
.MP3Imports as MP3 compressed format for longer music tracks.
.OGGNote: the OGG compressed audio format is incompatible with some Android devices, so Unity does not support it for the Android platform. Please use MP3 compressed sounds instead.

Import Settings

When you are importing an audio file, you can select its final format and choose to force it to stereo or mono channels. To access the Import Settings, select the Audio Clip in the Project View and find the Audio Importer in the Inspector. Here, you can compress the Clip into Ogg Vorbis format, force it into Mono or Stereo playback, and tweak other options, such as the very important Decompress On Load setting.

Read more about using MP3 Compressed or Uncompressed audio on the Audio Clip Component Reference page.

Once sound files are imported, they can be attached to any GameObject. The Audio file will create an Audio Source Component automatically when you drag it onto a GameObject.

Page last updated: 2013-07-12



Meshes

There are three tabs in the Model Importer - Model, Rig, and Animations.

This section covers these tabs in greater detail.

Page last updated: 2013-05-01



3D-formats

Importing meshes into Unity can be achieved from two main types of files:

  1. Exported 3D file formats, such as .FBX or .OBJ
  2. Proprietary 3D application files, such as .Max and .Blend file formats from 3D Studio Max or Blender for example.

Either should enable you to get your meshes into Unity, but there are considerations as to which type you choose:

Exported 3D files

Unity can read .FBX, .dae (Collada), .3DS, .dxf and .obj files, FBX exporters can be found here and obj or Collada exporters can also be found for many applications

Advantages:

Disadvantages:

Proprietary 3D application files

Unity can also import, through conversion: Max, Maya, Blender, Cinema4D, Modo, Lightwave & Cheetah3D files, e.g. .MAX, .MB, .MA etc.

Advantages:

Disadvantages:

Page last updated: 2013-07-17



Materials

There is a close relationship between Materials and Shaders in Unity. Shaders contain code that defines what kind of properties and assets to use. Materials allow you to adjust properties and assign assets.


A Shader is implemented through a Material

To create a new Material, use Assets->Create->Material from the main menu or the Project View context menu. Once the Material has been created, you can apply it to an object and tweak all of its properties in the Inspector. To apply it to an object, just drag it from the Project View to any object in the Scene or Hierarchy.

Setting Material Properties

You can select which Shader you want any particular Material to use. Simply expand the Shader drop-down in the Inspector, and choose your new Shader. The Shader you choose will dictate the available properties to change. The properties can be colors, sliders, textures, numbers, or vectors. If you have applied the Material to an active object in the Scene, you will see your property changes applied to the object in real-time.

There are two ways to apply a Texture to a property.

  1. Drag it from the Project View on top of the Texture square
  2. Click the Select button, and choose the texture from the drop-down list that appears

Two placement options are available for each Texture:

TilingScales the texture along the different axes.
OffsetSlides the texture around.

Built-in Shaders

A set of built-in Shaders are installed with the Unity editor. Over eighty shaders are available - the main ones used for texturing game objects fall into the following categories:-

In each group, built-in shaders range by complexity, from the simple VertexLit to the complex Parallax Bumped with Specular. For more information about performance of Shaders, please read the built-in Shader performance page


In addition to the main game object shaders, there are a number of other categories for specialised purposes:-

Also, some of these shaders have special versions for use with mobile devices.

Shader technical details

Unity has an extensive Shader system, allowing you to tweak the look of all in-game graphics. It works like this:

A Shader basically defines a formula for how the in-game shading should look. Within any given Shader is a number of properties (typically textures). Shaders are implemented through Materials, which are attached directly to individual GameObjects. Within a Material, you will choose a Shader, then define the properties (usually textures and colors, but properties can vary) that are used by the Shader.

This is rather complex, so let's look at a workflow diagram:

On the left side of the graph is the Carbody Shader. 2 different Materials are created from this: Blue car Material and Red car Material. Each of these Materials have 2 textures assigned; the Car Texture defines the main texture of the car, and a Color FX texture. These properties are used by the shader to make the car finish look like 2-tone paint. This can be seen on the front of the red car: it is yellow where it faces the camera and then fades towards purple as the angle increases. The car materials are attached to the 2 cars. The car wheels, lights and windows don't have the color change effect, and must hence use a different Material. At the bottom of the graph there is a Simple Metal Shader. The Wheel Material is using this Shader. Note that even though the same Car Texture is reused here, the end result is quite different from the car body, as the Shader used in the Material is different.

To be more specific, a Shader defines:

A Material defines:

Shaders are meant to be written by graphics programmers. They are created using the ShaderLab language, which is quite simple. However, getting a shader to work well on a variety graphics cards is an involved job and requires a fairly comprehensive knowledge of how graphics cards work.

A number of shaders are built into Unity directly, and some more come in the Standard Assets Library. For further information about shaders, see the Built-in Shader Guide.

Page last updated: 2013-10-14



Textures

Textures bring your Meshes, Particles, and interfaces to life! They are image or movie files that you lay over or wrap around your objects. As they are so important, they have a lot of properties.

The shaders you use for your objects put specific requirements on which textures you need, but the basic principle is that you can put any image file inside your project. If it meets the size requirements (specified below), it will get imported and optimized for game use. This extends to multi-layer Photoshop or TIFF files - they are flattened on import, so there is no size penalty for your game. Note that this flattening happens internally to Unity, and is optional, so you can continue to save and import your PSD files with layers intact. The PSD file is not flattened, in other words.

Properties

The Texture Inspector looks a bit different from most others:

The inspector is split into two sections, the Texture Importer and the texture preview.

Texture Importer

Textures all come from image files in your Project Folder. How they are imported is specified by the Texture Importer. You change these by selecting the file texture in the Project View and modifying the Texture Importer in the Inspector.

The topmost item in the inspector is the Texture Type menu that allows you to select the type of texture you want to create from the source image file.

Texture TypeSelect this to set basic parameters depending on the purpose of your texture.
TextureThis is the most common setting used for all the textures in general.
Normal MapSelect this to turn the color channels into a format suitable for real-time normal mapping. See the Details section at the end of the page..
SpriteThis must be selected if your texture will be used in a 2D game as a Sprite.
GUIUse this if your texture is going to be used on any HUD/GUI Controls.
ReflectionAlso known as Cube Maps, used to create reflections on textures. check Cubemap Textures for more info.
CookieThis sets up your texture with the basic parameters used for the Cookies of your lights
AdvancedSelect this when you want to have specific parameters on your texture and you want to have total control over your texture.

Basic Texture Settings Selected
Alpha From GrayscaleIf enabled, an alpha transparency channel will be generated by the image's existing values of light & dark.
Wrap ModeSelects how the Texture behaves when tiled:
RepeatThe Texture repeats (tiles) itself
ClampThe Texture's edges get stretched
Filter ModeSelects how the Texture is filtered when it gets stretched by 3D transformations:
PointThe Texture becomes blocky up close
BilinearThe Texture becomes blurry up close
TrilinearLike Bilinear, but the Texture also blurs between the different mip levels
Aniso LevelIncreases texture quality when viewing the texture at a steep angle. Good for floor and ground textures. See the Details section at the end of the page.

Normal Map Settings in the Texture Importer
Create from GreyscaleIf this is enabled then Bumpiness and Filtering options will be shown.
BumpinessControl the amount of bumpiness.
FilteringDetermine how the bumpiness is calculated:
SmoothThis generates normal maps that are quite smooth.
SharpAlso known as a Sobel filter. this generates normal maps that are sharper than Standard.
Wrap ModeSelects how the Texture behaves when tiled:
RepeatThe Texture repeats (tiles) itself
ClampThe Texture's edges get stretched
Filter ModeSelects how the Texture is filtered when it gets stretched by 3D transformations:
PointThe Texture becomes blocky up close
BilinearThe Texture becomes blurry up close
TrilinearLike Bilinear, but the Texture also blurs between the different mip levels
Aniso LevelIncreases texture quality when viewing the texture at a steep angle. Good for floor and ground textures. See the Details section at the end of the page.

GUI Settings for the Texture Importer
Filter ModeSelects how the Texture is filtered when it gets stretched by 3D transformations:
PointThe Texture becomes blocky up close
BilinearThe Texture becomes blurry up close
TrilinearLike Bilinear, but the Texture also blurs between the different mip levels

Sprite settings for the Texture Importer
Sprite modeSelects how the the sprite graphic will be extracted from the image.
SingleThe sprite image will be used in isolation.
MultipleMultiple related sprites (eg, animation frames) will use the same pattern. This also shows a button to launch the Sprite Editor.
Packing TagThe name of an optional sprite atlas into which this texture should be packed.
Pixels To UnitsThe number of pixels of width/height in the sprite image that will correspond to one distance unit in world space.
PivotThe point in the image where the sprite's local coordinate system originates (center, top-left, etc).
Filter ModeSelects how the Texture is filtered when it gets stretched by transformations:
PointThe Texture becomes blocky up close
BilinearThe Texture becomes blurry up close
TrilinearLike Bilinear, but the Texture also blurs between the different mip levels

Cursor settings for the Texture Importer
Wrap ModeSelects how the Texture behaves when tiled:
RepeatThe Texture repeats (tiles) itself
ClampThe Texture's edges get stretched
Filter ModeSelects how the Texture is filtered when it gets stretched by 3D transformations:
PointThe Texture becomes blocky up close
BilinearThe Texture becomes blurry up close
TrilinearLike Bilinear, but the Texture also blurs between the different mip levels

Reflection Settings in the Texture Importer
MappingThis determines how the texture will be mapped to a cubemap.
Sphere MappedMaps the texture to a "sphere like" cubemap.
CylindricalMaps the texture to a cylinder, use this when you want to use reflections on objects that are like cylinders.
Simple SphereMaps the texture to a simple sphere, deforming the reflection when you rotate it.
Nice SphereMaps the texture to a sphere, deforming it when you rotate but you still can see the texture's wrap
6 Frames LayoutThe texture contains six images arranged in one of the standard cubemap layouts, cross or sequence (+x -x +y -y +z -z) and the images can be in either horizontal or vertical orientation.
Fixup edge seamsRemoves visual artifacts at the joined edges of the map image(s), which will be visible with glossy reflections.
Filter ModeSelects how the Texture is filtered when it gets stretched by 3D transformations:
PointThe Texture becomes blocky up close
BilinearThe Texture becomes blurry up close
TrilinearLike Bilinear, but the Texture also blurs between the different mip levels
Aniso LevelIncreases texture quality when viewing the texture at a steep angle. Good for floor and ground textures. See the Details section at the end of the page.

An interesting way to add a lot of visual detail to your scenes is to use Cookies - greyscale textures you use to control the precise look of in-game lighting. This is fantastic for making moving clouds and giving an impression of dense foliage. The Light page has more info on all this, but the main thing is that for textures to be usable for cookies you just need to set the Texture Type to Cookie.


Cookie Settings in the Texture Importer
Light TypeType of light that the texture will be applied to. (This can be Spotlight, Point or Directional lights). For Directional Lights this texture will tile, so in the texture inspector, you must set the Edge Mode to Repeat; for SpotLights You should keep the edges of your cookie texture solid black in order to get the proper effect. In the Texture Inspector, set the Edge Mode to Clamp.
Mapping(Point light only) Options for mapping the texture onto the spherical cast of the point light.
Sphere MappedMaps the texture to a "sphere like" cubemap.
CylindricalMaps the texture to a cylinder, use this when you want to use reflections on objects that are like cylinders.
Simple SphereMaps the texture to a simple sphere, deforming the reflection when you rotate it.
Nice SphereMaps the texture to a sphere, deforming it when you rotate but you still can see the texture's wrap
6 Frames LayoutThe texture contains six images arranged in one of the standard cubemap layouts, cross or sequence (+x -x +y -y +z -z) and the images can be in either horizontal or vertical orientation.
Fixup edge seams(Point light only) Removes visual artifacts at the joined edges of the map image(s).
Alpha from GreyscaleIf enabled, an alpha transparency channel will be generated by the image's existing values of light & dark.

Lightmap settings in the Texture Importer
Filter ModeSelects how the Texture is filtered when it gets stretched by 3D transformations:
PointThe Texture becomes blocky up close
BilinearThe Texture becomes blurry up close
TrilinearLike Bilinear, but the Texture also blurs between the different mip levels
Aniso LevelIncreases texture quality when viewing the texture at a steep angle. Good for floor and ground textures. See the Details section at the end of the page.

The Advanced Texture Importer Settings dialog
Non Power of 2If texture has non-power-of-two size, this will define a scaling behavior at import time. See the Details section at the end of the page.
NoneTexture size will be kept as-is.
To nearestTexture will be scaled to the nearest power-of-two size at import time. For instance 257x511 texture will become 256x512. Note that PVRTC formats require textures to be square (width equal to height), therefore final size will be upscaled to 512x512.
To largerTexture will be scaled to the next larger power-of-two size at import time. For instance 257x511 texture will become 512x512.
To smallerTexture will be scaled to the next smaller power-of-two size at import time. For instance 257x511 texture will become 256x256.
Generate Cube MapGenerates a cubemap from the texture using different generation methods.
SpheremapMaps the texture to a "sphere like" cubemap.
CylindricalMaps the texture to a cylinder, use this when you want to use reflections on objects that are like cylinders.
SimpleSpheremapMaps the texture to a simple sphere, deforming the reflection when you rotate it.
NiceSpheremapMaps the texture to a sphere, deforming it when you rotate but you still can see the texture's wrap
FacesVerticalThe texture contains the six faces of the cube arranged in a vertical strip in the order +x -x +y -y +z -z.
FacesHorizontalThe texture contains the six faces of the cube arranged in a horizontal strip in the order +x -x +y -y +z -z.
CrossVerticalThe texture contains the six faces of the cube arranged in a vertically oriented cross.
CrossHorizontalThe texture contains the six faces of the cube arranged in a horizontally oriented cross.
Read/Write EnabledSelect this to enable access to the texture data from scripts (GetPixels, SetPixels and other Texture2D functions). Note however that a copy of the texture data will be made, doubling the amount of memory required for texture asset. Use only if absolutely necessary. This is only valid for uncompressed and DTX compressed textures, other types of compressed textures cannot be read from. Disabled by default.
Import TypeThe way the image data is interpreted.
DefaultStandard texture.
Normal MapTexture is treated as a normal map (enables other options)
LightmapTexture is treated as a lightmap (disables other options)
Alpha from grayscale(Default mode only) Generates the alpha channel from the luminance information in the image
Create from grayscale(Normal map mode only) Creates the map from the luminance information in the image
Bypass sRGB sampling(Default mode only) Use the exact colour values from the image rather than compensating for gamma (useful when the texture is for GUI or used as a way to encode non-image data)
Generate Mip MapsSelect this to enable mip-map generation. Mip maps are smaller versions of the texture that get used when the texture is very small on screen. See the Details section at the end of the page.
In Linear SpaceGenerate mipmaps in linear colour space.
Border Mip MapsSelect this to avoid colors seeping out to the edge of the lower Mip levels. Used for light cookies (see below).
Mip Map FilteringTwo ways of mip map filtering are available to optimize image quality:
BoxThe simplest way to fade out the mipmaps - the mip levels become smoother and smoother as they go down in size.
KaiserA sharpening Kaiser algorithm is run on the mip maps as they go down in size. If your textures are too blurry in the distance, try this option.
Fade Out MipmapsEnable this to make the mipmaps fade to gray as the mip levels progress. This is used for detail maps. The left most scroll is the first mip level to begin fading out at. The rightmost scroll defines the mip level where the texture is completely grayed out
Wrap ModeSelects how the Texture behaves when tiled:
RepeatThe Texture repeats (tiles) itself
ClampThe Texture's edges get stretched
Filter ModeSelects how the Texture is filtered when it gets stretched by 3D transformations:
PointThe Texture becomes blocky up close
BilinearThe Texture becomes blurry up close
TrilinearLike Bilinear, but the Texture also blurs between the different mip levels
Aniso LevelIncreases texture quality when viewing the texture at a steep angle. Good for floor and ground textures. See the Details section at the end of the page.

Per-Platform Overrides

When you are building for different platforms, you have to think about the resolution of your textures for the target platform, the size and the quality. You can set default options and then override the defaults for a specific platform.


Default settings for all platforms.
Max Texture SizeThe maximum imported texture size. Artists often prefer to work with huge textures - scale the texture down to a suitable size with this.
Texture FormatWhat internal representation is used for the texture. This is a tradeoff between size and quality. In the examples below we show the final size of a in-game texture of 256 by 256 pixels:
CompressedCompressed RGB texture. This is the most common format for diffuse textures. 4 bits per pixel (32 KB for a 256x256 texture).
16 bitLow-quality truecolor. Has 16 levels of red, green, blue and alpha.
TruecolorTruecolor, this is the highest quality. At 256 KB for a 256x256 texture.

If you have set the Texture Type to Advanced then the Texture Format has different values.

Desktop

Texture FormatWhat internal representation is used for the texture. This is a tradeoff between size and quality. In the examples below we show the final size of an in-game texture of 256 by 256 pixels:
RGB Compressed DXT1Compressed RGB texture. This is the most common format for diffuse textures. 4 bits per pixel (32 KB for a 256x256 texture).
RGBA Compressed DXT5Compressed RGBA texture. This is the main format used for diffuse & specular control textures. 1 byte/pixel (64 KB for a 256x256 texture).
RGB 16 bit65 thousand colors with no alpha. Compressed DXT formats use less memory and usually look better. 128 KB for a 256x256 texture.
RGB 24 bitTruecolor but without alpha. 192 KB for a 256x256 texture.
Alpha 8 bitHigh quality alpha channel but without any color. 64 KB for a 256x256 texture.
RGBA 16 bitLow-quality truecolor. Has 16 levels of red, green, blue and alpha. Compressed DXT5 format uses less memory and usually looks better. 128 KB for a 256x256 texture.
RGBA 32 bitTruecolor with alpha - this is the highest quality. At 256 KB for a 256x256 texture, this one is expensive. Most of the time, DXT5 offers sufficient quality at a much smaller size. The main way this is used is for normal maps, as DXT compression there often carries a visible quality loss.

iOS

Texture FormatWhat internal representation is used for the texture. This is a tradeoff between size and quality. In the examples below we show the final size of a in-game texture of 256 by 256 pixels:
RGB Compressed PVRTC 4 bitsCompressed RGB texture. This is the most common format for diffuse textures. 4 bits per pixel (32 KB for a 256x256 texture)
RGBA Compressed PVRTC 4 bitsCompressed RGBA texture. This is the main format used for diffuse & specular control textures or diffuse textures with transparency. 4 bits per pixel (32 KB for a 256x256 texture)
RGB Compressed PVRTC 2 bitsCompressed RGB texture. Lower quality format suitable for diffuse textures. 2 bits per pixel (16 KB for a 256x256 texture)
RGBA Compressed PVRTC 2 bitsCompressed RGBA texture. Lower quality format suitable for diffuse & specular control textures. 2 bits per pixel (16 KB for a 256x256 texture)
RGB Compressed DXT1Compressed RGB texture. This format is not supported on iOS, but kept for backwards compatibility with desktop projects.
RGBA Compressed DXT5Compressed RGBA texture. This format is not supported on iOS, but kept for backwards compatibility with desktop projects.
RGB 16 bit65 thousand colors with no alpha. Uses more memory than PVRTC formats, but could be more suitable for UI or crisp textures without gradients. 128 KB for a 256x256 texture.
RGB 24 bitTruecolor but without alpha. 192 KB for a 256x256 texture.
Alpha 8 bitHigh quality alpha channel but without any color. 64 KB for a 256x256 texture.
RGBA 16 bitLow-quality truecolor. Has 16 levels of red, green, blue and alpha. Uses more memory than PVRTC formats, but can be handy if you need exact alpha channel. 128 KB for a 256x256 texture.
RGBA 32 bitTruecolor with alpha - this is the highest quality. At 256 KB for a 256x256 texture, this one is expensive. Most of the time, PVRTC formats offers sufficient quality at a much smaller size.
Compression qualityChoose Fast for quickest performance, Best for the best image quality and Normal for a balance between the two.

Android

Texture FormatWhat internal representation is used for the texture. This is a tradeoff between size and quality. In the examples below we show the final size of a in-game texture of 256 by 256 pixels:
RGB Compressed DXT1Compressed RGB texture. Supported by Nvidia Tegra. 4 bits per pixel (32 KB for a 256x256 texture).
RGBA Compressed DXT5Compressed RGBA texture. Supported by Nvidia Tegra. 6 bits per pixel (64 KB for a 256x256 texture).
RGB Compressed ETC 4 bitsCompressed RGB texture. This is the default texture format for Android projects. ETC1 is part of OpenGL ES 2.0 and is supported by all OpenGL ES 2.0 GPUs. It does not support alpha. 4 bits per pixel (32 KB for a 256x256 texture)
RGB Compressed PVRTC 2 bitsCompressed RGB texture. Supported by Imagination PowerVR GPUs. 2 bits per pixel (16 KB for a 256x256 texture)
RGBA Compressed PVRTC 2 bitsCompressed RGBA texture. Supported by Imagination PowerVR GPUs. 2 bits per pixel (16 KB for a 256x256 texture)
RGB Compressed PVRTC 4 bitsCompressed RGB texture. Supported by Imagination PowerVR GPUs. 4 bits per pixel (32 KB for a 256x256 texture)
RGBA Compressed PVRTC 4 bitsCompressed RGBA texture. Supported by Imagination PowerVR GPUs. 4 bits per pixel (32 KB for a 256x256 texture)
RGB Compressed ATC 4 bitsCompressed RGB texture. Supported by Qualcomm Snapdragon. 4 bits per pixel (32 KB for a 256x256 texture).
RGBA Compressed ATC 8 bitsCompressed RGBA texture. Supported by Qualcomm Snapdragon. 6 bits per pixel (64 KB for a 256x256 texture).
RGB 16 bit65 thousand colors with no alpha. Uses more memory than the compressed formats, but could be more suitable for UI or crisp textures without gradients. 128 KB for a 256x256 texture.
RGB 24 bitTruecolor but without alpha. 192 KB for a 256x256 texture.
Alpha 8 bitHigh quality alpha channel but without any color. 64 KB for a 256x256 texture.
RGBA 16 bitLow-quality truecolor. The default compression for the textures with alpha channel. 128 KB for a 256x256 texture.
RGBA 32 bitTruecolor with alpha - this is the highest quality compression for the textures with alpha. 256 KB for a 256x256 texture.
Compression qualityChoose Fast for quickest performance, Best for the best image quality and Normal for a balance between the two.

Unless you're targeting a specific hardware, like Tegra, we'd recommend using ETC1 compression. If needed you could store an external alpha channel and still benefit from lower texture footprint. If you absolutely want to store an alpha channel in a texture, RGBA16 bit is the compression supported by all hardware vendors.

Textures can be imported from DDS files but only DXT or uncompressed pixel formats are currently supported.

If your app utilizes an unsupported texture compression, the textures will be uncompressed to RGBA 32 and stored in memory along with the compressed ones. So in this case you lose time decompressing textures and lose memory storing them twice. It may also have a very negative impact on rendering performance.

Flash

FormatImage format
RGB JPG CompressedRGB image data compressed in JPG format
RGBA JPG CompressedRGBA image data (ie, with alpha) compressed in JPG format
RGB 24-bitUncompressed RGB image data, 8 bits per channel
RGBA 32-bitUncompressed RGBA image data, 8 bits per channel

Details

Supported Formats

Unity can read the following file formats: PSD, TIFF, JPG, TGA, PNG, GIF, BMP, IFF, PICT. It should be noted that Unity can import multi-layer PSD & TIFF files just fine. They are flattened automatically on import but the layers are maintained in the assets themselves, so you don't lose any of your work when using these file types natively. This is important as it allows you to just have one copy of your textures that you can use from Photoshop, through your 3D modelling app and into Unity.

Texture Sizes

Ideally texture sizes should be powers of two on the sides. These sizes are as follows: 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048 etc. pixels. The textures do not have to be square, i.e. width can be different from height. Note that each platform may impose maximum texture sizes.

It is possible to use other (non power of two - "NPOT") texture sizes with Unity. Non power of two texture sizes generally take slightly more memory and might be slower to read by the GPU, so for performance it's best to use power of two sizes whenever you can. If the platform or GPU does not support NPOT texture sizes, then Unity will scale and pad the texture up to next power of two size, which will use even more memory and make loading slower (in practice, this always happens on Flash and some older Android devices). In general you'd want to use non power of two sizes only for GUI purposes.

Non power of two texture assets can be scaled up at import time using the Non Power of 2 option in the advanced texture type in the import settings.

UV Mapping

When mapping a 2D texture onto a 3D model, some sort of wrapping is done. This is called UV mapping and is done in your 3D modelling app. Inside Unity, you can scale and move the texture using Materials. Scaling normal & detail maps is especially useful.

Mip Maps

Mip Maps are a list of progressively smaller versions of an image, used to optimise performance on real-time 3D engines. Objects that are far away from the camera use the smaller texture versions. Using mip maps uses 33% more memory, but not using them can be a huge performance loss. You should always use mipmaps for in-game textures; the only exceptions are textures that will never be minified (e.g. GUI textures).

Normal Maps

Normal maps are used by normal map shaders to make low-polygon models look as if they contain more detail. Unity uses normal maps encoded as RGB images. You also have the option to generate a normal map from a grayscale height map image.

Detail Maps

If you want to make a terrain, you normally use your main texture to show where there are areas of grass, rocks sand, etc... If your terrain has a decent size, it will end up very blurry. Detail textures hide this fact by fading in small details as your main texture gets up close.

When drawing detail textures, a neutral gray is invisible, white makes the main texture twice as bright and black makes the main texture completely black.

Reflections (Cube Maps)

If you want to use texture for reflection maps (e.g. use the Reflective built-in shaders), you need to use Cubemap Textures.

Anisotropic filtering

Anisotropic filtering increases texture quality when viewed from a grazing angle, at some expense of rendering cost (the cost is entirely on the graphics card). Increasing anisotropy level is usually a good idea for ground and floor textures. In Quality Settings anisotropic filtering can be forced for all textures or disabled completely.


No anisotropy (left) / Maximum anisotropy (right) used on the ground texture

Page last updated: 2007-11-16



SpriteEditor

Sometimes a sprite texture will contain just a single graphic element but it is often more convenient to combine several related graphics together into a single image. For example, the image could contain contain component parts of a single character, as with a car whose wheels move independently of the body. Unity makes it easy to extract elements from an composite image by providing a Sprite Editor for the purpose.

Opening the Sprite Editor

To use the Sprite Editor, you will first need to ensure that your sprite texture has the Sprite Mode set to Manual in the texture importer (and also remember to click the Apply button after the change). When you do this, a button to open the Sprite Editor will appear in the inspector. You can also open the editor by selecting a sprite texture from the Project panel and selecting Window > Sprite Editor from the menu. The window will look something like the following:-

Along with the composite image, you will see a number of controls in the bar at the top of the window. The slider at the top right controls the zoom, while the color bar button to its left chooses whether you view the image itself or its alpha levels. The most important control is the Slice menu at the top left, which gives you options for separating the elements of the image automatically. Finally, the Apply and Revert buttons allow you to keep or discard any changes you have made.

Using the Editor

The most direct way to use the editor is to identify the elements manually. If you click on the image, you will see a rectangular selection area appear with handles in the corners. You can drag the handles or the edges of the rectangle to resize it around a specific element. Having isolated an element, you can add another by dragging a new rectangle in a separate part of the image. You'll notice that when you have a rectangle selected, a panel appears in the bottom left of the window:-

The controls in the panel let you choose a name for the sprite graphic and set the position and size of the rectangle by its coordinates. The Trim button next to the position settings will resize the rectangle so that it fits tightly around the edge of the graphic based on transparency. There are also settings for the sprite's pivot, which Unity uses as the coordinate origin and main "anchor point" of the graphic. You can choose from a number of default rectangle-relative positions (eg, Center, Top Right, etc) or use custom coordinates.

Automatic slicing

Isolating the sprite rectangles manually works well but in many cases, Unity can save you work by detecting the graphic elements and extracting them for you automatically. If you click on the Slice menu in the control bar, you will see this panel:-

With the slicing type set to Automatic, the editor will attempt to guess the boundaries of sprite elements by transparency. You can set a minimum size for any rectangle to prevent tiny details ending up in their own separate sprites. You can also set a default pivot for each identified sprite. The Method menu lets you choose how to deal with existing selections in the window. The Delete existing option will simply replace whatever is already selected, Smart will attempt to create new rectangles while retaining or adjusting existing ones, and Safe will add new rectangles without changing anything already in place.

A Grid option is also available for the slicing type, which is very useful when the sprites have already been laid out in a regular pattern during creation:-

The Pixel Size values determine the height and width of the tiles in pixels.

Note that after either of the two automatic slicing methods has been used, the generated rectangles can still be edited manually. You can let Unity handle the rough definition of the sprite boundaries and pivots and then do any necessary fine tuning yourself.

Page last updated: 2013-10-08



SpritePacker

When designing sprite graphics, it is convenient to work with a separate texture file for each character. However, a significant portion of a sprite texture will often be taken up by the empty space between the graphic elements and this space will result in wasted video memory at runtime. For optimal performance, it is best to pack graphics from several sprite textures tightly together within a single texture known as an atlas. Unity provides a Sprite Packer utility to automate the process of generating atlases from the individual sprite textures.

Unity handles the generation and use of sprite atlas textures behind the scenes so that the user needs to do no manual assignment. The atlas can optionally be packed on entering Play mode or during a build and the graphics for a sprite object will be obtained from the atlas once it is generated.

Using the Sprite Packer

If you open the Sprite Packer window (menu: Window > Sprite Packer) and click the Pack button in the top-left corner, you will see the arrangement of the textures packed within the atlas.

If you select a sprite in the Project panel, this will also be highlighted to show its position in the atlas. The outline is actually the render mesh outline and it also defines the area used for tight packing.

The toolbar at the top of the Sprite Packer window has a number of controls that affect packing and viewing. The Pack buttons initiates the packing operation but will not force any update if the atlas hasn't changed since it was last packed. (A related Repack button will appear when you implement a custom packing policy as explained in Customizing the Sprite Packer below). The View Atlas and Page # menus allow you to choose which page of which atlas is shown in the window (a single atlas may be split into more than one "page" if there is not enough space for all sprites in the maximum texture size). The menu next to the page number selects which "packing policy" is used for the atlas (see below). At the right of the toolbar are two controls to zoom the view and to switch between color and alpha display for the atlas.

You can configure the Sprite Packer from the Editor settings (menu: Edit > Project Settings > Editor). The sprite packing mode can be set to Disabled, Enabled for Builds (ie, packing is used for builds but not Play mode) or Always Enabled (ie, packing is enabled for both Play mode and builds).

Packing Policy

The Sprite Packer uses a packing policy to decide how assign sprites into atlases. It is possible to create your own packing policies (see below) but the Default Packer Policy option is always available. With this policy, the Packing Tag property in the Texture Importer directly selects the name of the atlas where the sprite will be packed and so all sprites with the same packing tag will be packed in the same atlas. Atlases are then further sorted by the texture import settings so that they match whatever the user sets for the source textures.

Customizing the Sprite Packer

The DefaultPackerPolicy option is sufficient for most uses but you can also implement your own custom packing policy if you need to. To do this, you need to implement the UnityEditor.Sprites.IPackerPolicy interface for a class in an editor script. This interface requires the following methods:-

DefaultPackerPolicy uses tight packing (see SpritePackingMode) by default. Custom policies can override this and instead use rectangle packing. This is useful if you're doing texture-space effects or would like to use a different mesh for rendering the Sprite.

Other

DefaultPackerPolicy

class DefaultPackerPolicy : IPackerPolicy
{
	private class Entry
	{
		public Sprite         sprite;
		public AtlasSettings  settings;
		public string         tag;
		public SpriteMeshType meshType;
	}

	public int GetVersion()
	{
		return 1;
	}

	public void OnGroupAtlases(BuildTarget target, PackerJob job, TextureImporter[] textureImporters)
	{
		List<Entry> entries = new List<Entry>();

		foreach (TextureImporter ti in textureImporters)
		{
			TextureImportInstructions ins = new TextureImportInstructions();
			ti.ReadTextureImportInstructions(ins, target);

			TextureImporterSettings tis = new TextureImporterSettings();
			ti.ReadTextureSettings(tis);

			Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath(ti.assetPath).Select(x => x as Sprite).Where(x => x != null).ToArray();
			foreach (Sprite sprite in sprites)
			{
				Entry entry = new Entry();
				entry.sprite = sprite;
				entry.settings.format = ins.desiredFormat;
				entry.settings.usageMode = ins.usageMode;
				entry.settings.colorSpace = ins.colorSpace;
				entry.settings.compressionQuality = ins.compressionQuality;
				entry.settings.filterMode = ti.filterMode;
				entry.settings.maxWidth = 2048;
				entry.settings.maxHeight = 2048;
				entry.tag = ti.spritePackingTag;
				entry.meshType = tis.spriteMeshType;

				entries.Add(entry);
			}
		}

		// First split sprites into groups based on packing tag
		var tagGroups =
			from e in entries
			group e by e.tag;
		foreach (var tagGroup in tagGroups)
		{
			int page = 0;
			// Then split those groups into smaller groups based on texture settings
			var settingsGroups =
				from t in tagGroup
				group t by t.settings;
			foreach (var settingsGroup in settingsGroups)
			{
				string atlasName = string.Format("{0}", tagGroup.Key);
				if (settingsGroups.Count() > 1)
					atlasName += string.Format(" (Group {0})", page);

				job.AddAtlas(atlasName, settingsGroup.Key);
				foreach (Entry entry in settingsGroup)
				{
					SpritePackingMode packingMode = (entry.meshType == SpriteMeshType.Tight) ? SpritePackingMode.Tight : SpritePackingMode.Rectangle;
					job.AssignToAtlas(atlasName, entry.sprite, packingMode, SpritePackingRotation.None);
				}

				++page;
			}
		}
	}
}

Page last updated: 2013-10-29



Procedural Materials

Unity incorporates a new asset type known as Procedural Materials. These are essentially the same as standard Materials except that the textures they use can be generated at runtime rather than being predefined and stored.

The script code that generates a texture procedurally will typically take up much less space in storage and transmission than a bitmap image and so Procedural Materials can help reduce download times. Additionally, the generation script can be equipped with parameters that can be changed in order to vary the visual properties of the material at runtime. These properties can be anything from color variations to the size of bricks in a wall. Not only does this mean that many variations can be generated from a single Procedural Material but also that the material can be animated on a frame-by-frame basis. Many interesting visual effects are possible - imagine a character gradually turning to stone or acid damaging a surface as it touches.

Unity's Procedural Material system is based around an industry standard product called Substance, developed by Allegorithmic

Supported Platforms

In Unity, Procedural Materials are fully supported for standalone and webplayer build targets only (Windows and Mac OS X). For all other platforms, Unity will pre-render or bake them into ordinary Materials during the build. Although this clearly negates the runtime benefits of procedural generation, it is still useful to be able to create variations on a basic material in the editor.

Adding Procedural Materials to a Project

A Procedural Material is supplied as a Substance Archive file (SBSAR) which you can import like any other asset (drag and drop directly onto the Assets folder or use Assets->Import New Asset...). A Substance Archive asset contains one or more Procedural Materials and contains all the scripts and images required by these. Uncompiled SBS files are not supported.

Although they are implemented differently, Unity handles a Procedural Material just like any other Material. To assign a Procedural Material to a mesh, for example, you just drag and drop it onto the mesh exactly as you would with any other Material.

Procedural Properties

Each Procedural Material is a custom script which generates a particular type of material. These scripts are similar to Unity scripts in that they can have variables exposed for assignment in the inspector. For example, a "Brick Wall" Procedural Material could expose properties that let you set the number of courses of bricks, the colors of the bricks and the color of the mortar. This potentially offers infinite material variations from a single asset. These properties can also be set from a script at runtime in much the same way as the public variables of a MonoBehaviour script.

Procedural Materials can also incorporate complex texture animation. For example, you could animate the hands of the clock or cockroaches running across a floor.

Creating Procedural Materials From Scratch

Procedural Materials can work with any combination of procedurally generated textures and stored bitmaps. Additionally, included bitmap images can be filtered and modified before use. Unlike a standard Material, a Procedural Material can use vector images in the form of SVG files which allows for resolution-independent textures.

The design tools available for creating Procedural Materials from scratch use visual, node-based editing similar to the kind found in artistic tools. This makes creation accessible to artists who may have little or no coding experience. As an example, here is a screenshot from Allegorithmic's Substance Designer which shows a "brick wall" Procedural Material under construction:

Obtaining Procedural Materials

Since Unity's Procedural Materials are based on the industry standard Substance product, Procedural Material assets are readily available from internet sources, including Unity's own Asset Store. Allegorithmic's Substance Designer can be used to create Procedural Materials, but there are other applications (3D modelling apps, for example) that incorporate the Substance technology and work just as well with Unity.

Performance and Optimization

Procedural Materials inherently tend to use less storage than bitmap images. However, the trade-off is that they are based around scripts and running those scripts to generate materials requires some CPU and GPU resources. The more complex your Procedural Materials are, the greater their runtime overhead.

Procedural Materials support a form of caching whereby the material is only updated if its parameters have changed since it was last generated. Further to this, some materials may have many properties that could theoretically be changed and yet only a few will ever need to change at runtime. In such cases, you can inform Unity about the variables that will not change to help it cache as much data as possible from the previous generation of the material. This will often improve performance significantly.

Procedural Materials can refer to hidden, system-wide, variables, such as elapsed time or number of Procedural Material instances (this data can be useful for animations). Changes in the values of these variables can still force a Procedural Material to update even if none of the explicitly defined parameters change.

Procedural Materials can also be used purely as a convenience in the editor (ie, you can generate a standard Material by setting the parameters of a Procedural Material and then "baking" it). This will remove the runtime overhead of material generation but naturally, the baked materials can't be changed or animated during gameplay.

Using the Substance Player to Analyze Performance

Since the complexity of a Procedural Material can affect runtime performance, Allegorithmic incorporates profiling features in its Substance Player tool. This tool is available to download for free from Allegorithmic's website.

Substance Player uses the same optimized rendering engine as the one integrated into Unity, so its rendering measurement is more representative of performance in Unity than that of Substance Designer.

Page last updated: 2012-10-12



Video Files

Note: This is a Pro/Advanced feature only.

Desktop

Movie Textures are animated Textures that are created from a video file. By placing a video file in your project's Assets Folder, you can import the video to be used exactly as you would use a regular Texture.

Video files are imported via Apple QuickTime. Supported file types are what your QuickTime installation can play (usually .mov, .mpg, .mpeg, .mp4, .avi, .asf). On Windows movie importing requires Quicktime to be installed (download here).

Properties

The Movie Texture Inspector is very similar to the regular Texture Inspector.


Video files are Movie Textures in Unity
QualityCompression of the Ogg Theora video file. A higher value means higher quality, but larger file size

Details

When a video file is added to your Project, it will automatically be imported and converted to Ogg Theora format. Once your Movie Texture has been imported, you can attach it to any GameObject or Material, just like a regular Texture.

Playing the Movie

Your Movie Texture will not play automatically when the game begins running. You must use a short script to tell it when to play.

// this line of code will make the Movie Texture begin playing
renderer.material.mainTexture.Play();

Attach the following script to toggle Movie playback when the space bar is pressed:

function Update () {
	if (Input.GetButtonDown ("Jump")) {
		if (renderer.material.mainTexture.isPlaying) {
			renderer.material.mainTexture.Pause();
		}
		else {
			renderer.material.mainTexture.Play();
		}
	}
}

Note: If you have #pragma strict enabled in your code a MovieTexture object should be declared somewhere and the object should be initialized with renderer.material.mainTexture. Then isPlaying, Play() and Stop() should be called for this MovieTexture object.

For more information about playing Movie Textures, see the Movie Texture Script Reference page

Movie Audio

When a Movie Texture is imported, the audio track accompanying the visuals are imported as well. This audio appears as an AudioClip child of the Movie Texture.


The video's audio track appears as a child of the Movie Texture in the Project View

To play this audio, the Audio Clip must be attached to a GameObject, like any other Audio Clip. Drag the Audio Clip from the Project View onto any GameObject in the Scene or Hierarchy View. Usually, this will be the same GameObject that is showing the Movie. Then use audio.Play() to make the the movie's audio track play along with its video.

iOS

Movie Textures are not supported on iOS. Instead, full-screen streaming playback is provided using Handheld.PlayFullScreenMovie.

You need to keep your videos inside the StreamingAssets folder located in the Assets folder of your project.

Unity iOS supports any movie file types that play correctly on an iOS device, implying files with the extensions .mov, .mp4, .mpv, and .3gp and using one of the following compression standards:

For more information about supported compression standards, consult the iPhone SDK MPMoviePlayerController Class Reference.

As soon as you call Handheld.PlayFullScreenMovie the screen will fade from your current content to the designated background color. It might take some time before the movie is ready to play but in the meantime, the player will continue displaying the background color and may also display a progress indicator to let the user know the movie is loading. When playback finishes, the screen will fade back to your content.

The video player does not respect switching to mute while playing videos

As written above, video files are played using Apple's embedded player (as of SDK 3.2 and iPhone OS 3.1.2 and earlier). This contains a bug that prevents Unity switching to mute.

The video player does not respect the device's orientation

The Apple video player and iPhone SDK do not provide a way to adjust the orientation of the video. A common approach is to manually create two copies of each movie in landscape and portrait orientations. Then, the orientation of the device can be determined before playback so the right version of the movie can be chosen.

Android

Movie Textures are not supported on Android. Instead, full-screen streaming playback is provided using Handheld.PlayFullScreenMovie.

You need to keep your videos inside the StreamingAssets folder located in the Assets folder of your project.

Unity Android supports any movie file type supported by Android, (ie, files with the extensions .mp4 and .3gp) and using one of the following compression standards:

However, device vendors are keen on expanding this list, so some Android devices are able to play formats other than those listed, such as HD videos.

For more information about the supported compression standards, consult the Android SDK Core Media Formats documentation.

As soon as you call Handheld.PlayFullScreenMovie the screen will fade from your current content to the designated background color. It might take some time before the movie is ready to play but in the meantime, the player will continue displaying the background color and may also display a progress indicator to let the user know the movie is loading. When playback finishes, the screen will fade back to your content.

Page last updated: 2007-11-16



Audio Files

As with Meshes or Textures, the workflow for Audio File assets is designed to be smooth and trouble free. Unity can import almost every common file format but there are a few details that are useful to be aware of when working with Audio Files.

Audio in Unity is either Native or Compressed. Unity supports most common formats (see the list below) and will import an audio file when it is added to the project. The default mode is Native, where the audio data from the original file is imported unchanged. However, Unity can also compress the audio data on import, simply by enabling the Compressed option in the importer. (iOS projects can make use of the hardware decoder - see the iOS documentation for further details). The difference between Native and Compressed modes are as follows:-

Any Audio File imported into Unity is available from scripts as an Audio Clip instance, which is effectively just a container for the audio data. The clips must be used in conjunction with Audio Sources and an Audio Listener in order to actually generate sound. When you attach your clip to an object in the game, it adds an Audio Source component to the object, which has Volume, Pitch and a numerous other properties. While a Source is playing, an Audio Listener can "hear" all sources within range, and the combination of those sources gives the sound that will actually be heard through the speakers. There can be only one Audio Listener in your scene, and this is usually attached to the Main Camera.

Supported Formats

FormatCompressed as (Mac/PC)Compressed as (Mobile)
MPEG(1/2/3)Ogg VorbisMP3
Ogg VorbisOgg VorbisMP3
WAVOgg VorbisMP3
AIFFOgg VorbisMP3
MOD--
IT--
S3M--
XM--

See the Sound chapter in the Creating Gameplay section of this manual for more information on using sound in Unity.

Audio Clip

Audio Clips contain the audio data used by Audio Sources. Unity supports mono, stereo and multichannel audio assets (up to eight channels). The audio file formats that Unity can import are .aif, .wav, .mp3, and .ogg. Unity can also import tracker modules in the .xm, .mod, .it, and .s3m formats. The tracker module assets behave the same way as any other audio assets in Unity although no waveform preview is available in the asset import inspector.


The Audio Clip inspector

Properties

Audio FormatThe specific format that will be used for the sound at runtime.
NativeThis option offers higher quality at the expense of larger file size and is best for very short sound effects.
CompressedThe compression results in smaller files but with somewhat lower quality compared to native audio. This format is best for medium length sound effects and music.
3D SoundIf enabled, the sound will play back in 3D space. Both Mono and Stereo sounds can be played in 3D.
Force to monoIf enabled, the audio clip will be down-mixed to a single channel sound.
Load TypeThe method Unity uses to load audio assets at runtime.
Decompress on loadAudio files will be decompressed as soon as they are loaded. Use this option for smaller compressed sounds to avoid the performance overhead of decompressing on the fly. Be aware that decompressing sounds on load will use about ten times more memory than keeping them compressed, so don't use this option for large files.
Compressed in memoryKeep sounds compressed in memory and decompress while playing. This option has a slight performance overhead (especially for Ogg/Vorbis compressed files) so only use it for bigger files where decompression on load would use a prohibitive amount of memory. Note that, due to technical limitations, this option will silently switch to Stream From Disc (see below) for Ogg Vorbis assets on platforms that use FMOD audio.
Stream from discStream audio data directly from disc. The memory used by this option is typically a small fraction of the file size, so it is very useful for music or other very long tracks. For performance reasons, it is usually advisable to stream only one or two files from disc at a time but the number of streams that can comfortably be handled depends on the hardware.
CompressionAmount of Compression to be applied to a Compressed clip. Statistics about the file size can be seen under the slider. A good approach to tuning this value is to drag the slider to a place that leaves the playback "good enough" while keeping the file small enough for your distribution requirements.
Hardware Decoding(iOS only) On iOS devices, Apple's hardware decoder can be used resulting in lower CPU overhead during decompression. Check out platform specific details for more info.
Gapless looping(Android/iOS only) Use this when compressing a seamless looping audio source file (in a non-compressed PCM format) to ensure perfect continuity is preserved at the seam. Standard MPEG encoders introduce a short silence at the loop point, which will be audible as a brief "click" or "pop".

Importing Audio Assets

Unity supports both Compressed and Native Audio. Any type of file (except MP3/Ogg Vorbis) will be initially imported as Native. Compressed audio files must be decompressed by the CPU while the game is running, but have smaller file size. If Stream is checked the audio is decompressed on the fly, otherwise it is decompressed completely as soon as it loads. Native PCM formats (WAV, AIFF) have the benefit of giving higher fidelity without increasing the CPU overhead, but files in these formats are typically much larger than compressed files. Module files (.mod,.it,.s3m..xm) can deliver very high quality with an extremely low footprint.

As a general rule of thumb, Compressed audio (or modules) are best for long files like background music or dialog, while Native is better for short sound effects. You should tweak the amount of Compression using the compression slider. Start with high compression and gradually reduce the setting to the point where the loss of sound quality is perceptible. Then, increase it again slightly until the perceived loss of quality disappears.

Using 3D Audio

If an audio clip is marked as a 3D Sound then it will be played back so as to simulate its position in the game world's 3D space. 3D sounds emulate the distance and location of sounds by attenuating volume and panning across speakers. Both mono and multiple channel sounds can be positioned in 3D. For multiple channel audio, use the spread option on the Audio Source to spread and split out the discrete channels in speaker space. Unity offers a variety of options to control and fine-tune the audio behavior in 3D space - see the Audio Source component reference for further details.

Platform specific details

iOS

On mobile platforms compressed audio is encoded as MP3 to take advantage of hardware decompression.

To improve performance, audio clips can be played back using the Apple hardware codec. To enable this option, check the "Hardware Decoding" checkbox in the Audio Importer. Note that only one hardware audio stream can be decompressed at a time, including the background iPod audio.

If the hardware decoder is not available, the decompression will fall back on the software decoder (on iPhone 3GS or later, Apple's software decoder is used in preference to Unity's own decoder (FMOD)).

Android

On mobile platforms compressed audio is encoded as MP3 to take advantage of hardware decompression.

Page last updated: 2013-10-17



TrackerModules

Tracker Modules are essentially just packages of audio samples that have been modeled, arranged and sequenced programatically. The concept was introduced in the 1980's (mainly in conjunction with the Amiga computer) and has been popular since the early days of game development and demo culture.

Tracker Module files are similar to MIDI files in many ways. The tracks are scores that contain information about when to play the instruments, and at what pitch and volume and from this, the melody and rhythm of the original tune can be recreated. However, MIDI has a disadvantage in that the sounds are dependent on the sound bank available in the audio hardware, so MIDI music can sound different on different computers. In contrast, tracker modules include high quality PCM samples that ensure a similar experience regardless of the audio hardware in use.

Supported formats

Unity supports the four most common module file formats, namely Impulse Tracker (.it), Scream Tracker (.s3m), Extended Module File Format (.xm), and the original Module File Format (.mod).

Benefits of Using Tracker Modules

Tracker module files differ from mainstream PCM formats (.aif, .wav, .mp3, and .ogg) in that they can be very small without a corresponding loss of sound quality. A single sound sample can be modified in pitch and volume (and can have other effects applied), so it essentially acts as an "instrument" which can play a tune without the overhead of recording the whole tune as a sample. As a result, tracker modules lend themselves to games, where music is required but where a large file download would be a problem.

Third Party Tools and Further References

Currently, the most popular tools to create and edit Tracker Modules are MilkyTracker for OSX and OpenMPT for Windows. For more information and discussion, please see the blog post .mod in Unity from June 2010.

Page last updated: 2011-11-15



Scripting42

Scripting is an essential ingredient in all games. Even the simplest game will need scripts to respond to input from the player and arrange for events in the gameplay to happen when they should. Beyond that, scripts can be used to create graphical effects, control the physical behaviour of objects or even implement a custom AI system for characters in the game.

Scripting is a skill that takes some time and effort to learn; the intention of this section is not to teach you how to write script code from scratch but rather to explain the main concepts that apply to scripting in Unity.

Page last updated: 2013-03-25



CreatingAndUsingScripts

The behavior of GameObjects is controlled by the Components that are attached to them. Although Unity's built-in Components can be very versatile, you will soon find you need to go beyond what they can provide to implement your own gameplay features. Unity allows you to create your own Components using scripts. These allow you to trigger game events, modify Component properties over time and respond to user input in any way you like.

Unity supports three programming languages natively:

In addition to these, many other .NET languages can be used with Unity if they can compile a compatible DLL - see this page for further details.

Learning the art of programming and the use of these particular languages is beyond the scope of this introduction. However, there are many books, tutorials and other resources for learning how to program with Unity. See the Learning section of our website for further details.

Creating Scripts

Unlike most other assets, scripts are usually created within Unity directly. You can create a new script from the Create menu at the top left of the Project panel or by selecting Assets > Create > C# Script (or JavaScript/Boo script) from the main menu.

The new script will be created in whichever folder you have selected in the Project panel. The new script file's name will be selected, prompting you to enter a new name.

It is a good idea to enter the name of the new script at this point rather than editing it later. The name that you enter will be used to create the initial text inside the file, as described below.

Anatomy of a Script file

When you double-click a script asset in Unity, it will be opened in a text editor. By default, Unity will use MonoDevelop, but you can select any editor you like from the External Tools panel in Unity's preferences.

The initial contents of the file will look something like this:

using UnityEngine;
using System.Collections;

public class MainPlayer : MonoBehaviour {

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}
}

A script makes its connection with the internal workings of Unity by implementing a class which derives from the built-in class called MonoBehaviour. You can think of a class as a kind of blueprint for creating a new Component type that can be attached to GameObjects. Each time you attach a script component to a GameObject, it creates a new instance of the object defined by the blueprint. The name of the class is taken from the name you supplied when the file was created. The class name and file name must be the same to enable the script component to be attached to a GameObject.

The main things to note, however, are the two functions defined inside the class. The Update function is the place to put code that will handle the frame update for the GameObject. This might include movement, triggering actions and responding to user input, basically anything that needs to be handled over time during gameplay. To enable the Update function to do its work, it is often useful to be able to set up variables, read preferences and make connections with other GameObjects before any game action takes place. The Start function will be called by Unity before gameplay begins (ie, before the Update function is called for the first time) and is an ideal place to do any initialization.

Note to experienced programmers: you may be surprised that initialization of an object is not done using a constructor function. This is because the construction of objects is handled by the editor and does not take place at the start of gameplay as you might expect. If you attempt to define a constructor for a script component, it will interfere with the normal operation of Unity and can cause major problems with the project.

A Boo script follows roughly the same layout as a C# script but UnityScript works a bit differently:-

#pragma strict

function Start () {

}

function Update () {

}

Here, the Start and Update functions have the same meaning but the class is not explicitly declared. The script itself is assumed to define the class; it will implicitly derive from MonoBehaviour and take its name from the filename of the script asset.

Controlling a GameObject

As noted above, a script only defines a blueprint for a Component and so none of its code will be activated until an instance of the script is attached to a GameObject. You can attach a script by dragging the script asset to a GameObject in the hierarchy panel or to the inspector of the GameObject that is currently selected. There is also a Scripts submenu on the Component menu which will contain all the scripts available in the project, including those you have created yourself. The script instance looks much like any other Component in the Inspector:-

Once attached, the script will start working when you press Play and run the game. You can check this by adding the following code in the Start function:-

// Use this for initialization
void Start () {
	Debug.Log("I am alive!");
}

Debug.Log is a simple command that just prints a message to Unity's console output. If you press Play now, you should see the message at the bottom of the main Unity editor window and in the Console window (menu: Window > Console).

Variables

A script works much like any other component for the most part but you will notice that the Inspector item for the script looks a bit next to the other Components with their editable properties. You can allow values in the script to be edited from the Inspector using variables:-

using UnityEngine;
using System.Collections;

public class MainPlayer : MonoBehaviour {
	public string myName;

	// Use this for initialization
	void Start () {
		Debug.Log("I am alive and my name is " + myName);
	}

	// Update is called once per frame
	void Update () {

	}
}

This code creates an item in the Inspector labelled "My Name".

Unity creates the Inspector label by introducing a space wherever a capital letter occurs in the variable name. However, this is purely for display purposes and you should always use the variable name within your code. If you edit the name and then press Play, you will see that the message includes the text you entered.

In C# and Boo, you must declare a variable as public to see it in the Inspector. In UnityScript, variables are public by default unless you specify that they should be private:-

#pragma strict

private var invisibleVar: int;

function Start () {

}

Unity will actually let you change the value of a script's variables while the game is running. This is very useful for seeing the effects of changes directly without having to stop and restart. When gameplay ends, the values of the variables will be reset to whatever they were before you pressed Play. This ensures that you are free to tweak your object's settings without fear of doing any permanent damage.

Page last updated: 2013-03-25



ControllingGameObjectsComponents

In the Unity editor, you make changes to Component properties using the Inspector. So, for example, changes to the position values of the Transform Component will result in a change to the GameObject's position. Similarly, you can change the color of a Renderer's material or the mass of a Rigidbody with a corresponding effect on the appearance or behavior of the GameObject. For the most part, scripting is also about modifying Component properties to manipulate GameObjects. The difference, though, is that a script can vary a property's value gradually over time or in response to input from the user. By changing, creating and destroying objects at the right time, any kind of gameplay can be implemented.

Accessing Components

The simplest and most common case is where a script needs access to other Components attached to the same GameObject. As mentioned in the Introduction section, a Component is actually an instance of a class so the first step is to get a reference to the Component instance you want to work with. This is done with the GetComponent function. Typically, you want to assign the Component object to a variable, which is done in C# using the following syntax:-

void Start () {
	Rigidbody rb = GetComponent<Rigidbody>();
}

In UnityScript, the syntax is subtly different:-

function Start () {
	var rb = GetComponent.<Rigidbody>();
}

Once you have a reference to a Component instance, you can set the values of its properties much as you would in the Inspector:-

void Start () {
	Rigidbody rb = GetComponent<Rigidbody>();

	// Change the mass of the object's Rigidbody.
	rb.mass = 10f;
}

An extra feature that is not available in the Inspector is the possibility of calling functions on Component instances:-

void Start () {
	Rigidbody rb = GetComponent<Rigidbody>();

	// Add a force to the Rigidbody.
	rb.AddForce(Vector3.up * 10f);
}

Note also that there is no reason why you can't have more than one custom script attached to the same object. If you need to access one script from another, you can use GetComponent as usual and just use the name of the script class (or the filename) to specify the Component type you want.

If you attempt to retrieve a Component that hasn't actually been added to the GameObject then GetComponent will return null; you will get a null reference error at runtime if you try to change any values on a null object.

Since some Component types are very commonly used, Unity provides built-in variables to access them in the MonoBehaviour class, so you can use things like:-

void Start () {
	transform.position = Vector3.zero;
}

...without first having to use GetComponent to access the Transform Component. The full list of built-in Component variables is given in the MonoBehaviour script reference page. Note that as with GetComponent, if the desired Component isn't attached to the object then the variable will contain a null value.

Accessing Other Objects

Although they sometimes operate in isolation, it is common for scripts to keep track of other objects. For example, a pursuing enemy might need to know the position of the player. Unity provides a number of different ways to retrieve other objects, each appropriate to certain situations.

Linking Objects with Variables

The most straightforward way to find a related GameObject is to add a public GameObject variable to the script:-

public class Enemy : MonoBehaviour {
	public GameObject player;

	// Other variables and functions...
}

This variable will be visible in the Inspector like any other:-

You can now drag an object from the scene or Hierarchy panel onto this variable to assign it. The GetComponent function and Component access variables are available for this object as with any other, so you can use code like the following:-

public class Enemy : MonoBehaviour {
	public GameObject player;

	void Start() {
		// Start the enemy ten units behind the player character.
		transform.position = player.transform.position - Vector3.forward * 10f;
	}
}

Additionally, if declare a public variable of a Component type in your script, you can drag any GameObject that has that Component attached onto it. This will access the Component directly rather than the GameObject itself.

public Transform playerTransform;

Linking objects together with variables is most useful when you are dealing with individual objects that have permanent connections. You can use an array variable to link several objects of the same type, but the connections must still be made in the Unity editor rather than at runtime. It is often convenient to locate objects at runtime and Unity provides two basic ways to do this, as described below.

Finding Child Objects

Sometimes, a game scene will make use of a number of objects of the same type, such as enemies, waypoints and obstacles. These may need to be tracked by a particular script that supervises or reacts to them (eg, all waypoints may need to be available to a pathfinding script). Using variables to link these objects is a possibility but it will make the design process tedious if each new waypoint has to be dragged to a variable on a script. Likewise, if a waypoint is deleted then it is a nuisance to have to remove the variable reference to the missing object. In cases like this, it is often better to manage a set of objects by making them all children of one parent object. The child objects can be retreived using the parent's Transform Component (since all GameObjects implicitly have a Transform):-

public class WaypointManager : MonoBehaviour {
	public Transform waypoints;

	void Start() {
		waypoints = new Transform[transform.childCount];
		int i = 0;

		for (Transform t in transform) {
			waypoints[i++] = t;
		}
	}
}

You can also locate a specific child object by name using the Transform.Find function:-

transform.Find("Gun");

This can be useful when an object has a child that can be added and removed during gameplay. A weapon that can be picked up and put down is a good example of this.

Finding Objects by Name or Tag

It is always possible to locate GameObjects anywhere in the scene hierarchy as long as you have some information to identify them. Individual objects can be retrieved by name using the GameObject.Find function:-

GameObject player;

void Start() {
	player = GameObject.Find("MainHeroCharacter");
}

An object or a collection of objects can also be located by their tag using the GameObject.FindWithTag and GameObject.FindGameObjectsWithTag functions:-

GameObject player;
GameObject[] enemies;

void Start() {
	player = GameObject.FindWithTag("Player");
	enemies = GameObject.FindGameObjectsWithTag("Enemy");
}

Page last updated: 2013-03-25



EventFunctions

A script in Unity is not like the traditional idea of a program where the code runs continuously in a loop until it completes its task. Instead, Unity passes control to a script intermittently by calling certain functions that are declared within it. Once a function has finished executing, control is passed back to Unity. These functions are known as event functions since they are activated by Unity in response to events that occur during gameplay. Unity uses a naming scheme to identify which function to call for a particular event. For example, you will already have seen the Update function (called before a frame update occurs) and the Start function (called just before the object's first frame update). Many more event functions are available in Unity; the full list can be found in the script reference page for the MonoBehaviour class along with details of their usage. The following are some of the most common and important events.

Regular Update Events

A game is rather like an animation where the animation frames are generated on the fly. A key concept in games programming is that of making changes to position, state and behavior of objects in the game just before each frame is rendered. The Update function is the main place for this kind of code in Unity. Update is called before the frame is rendered and also before animations are calculated.

void Update() {
	float distance = speed * Time.deltaTime * Input.GetAxis("Horizontal");
	transform.Translate(Vector3.right * speed);
}

The physics engine also updates in discrete time steps in a similar way to the frame rendering. A separate event function called FixedUpdate is called just before each physics update. Since the physics updates and frame updates do not occur with the same frequency, you will get more accurate results from physics code if you place it in the FixedUpdate function rather than Update.

void FixedUpdate() {
	Vector3 force = transform.forward * driveForce * Input.GetAxis("Vertical");
	rigidbody.AddForce(force);
}

It is also useful sometimes to be able to make additional changes at a point after the Update and FixedUpdate functions have been called for all objects in the scene and after all animations have been calculated. An example is where a camera should remain trained on a target object; the adjustment to the camera's orientation must be made after the target object has moved. Another example is where the script code should override the effect of an animation (say, to make the character's head look towards a target object in the scene). The LateUpdate function can be used for these kinds of situations.

void LateUpdate() {
	Camera.main.transform.LookAt(target.transform);
}

Initialization Events

It is often useful to be able to call initialization code in advance of any updates that occur during gameplay. The function is called before the first frame or physics update on an object. The Awake function is called for each object in the scene at the time when the scene loads. Note that although the various objects' Start and Awake functions are called in arbitrary order, all the Awakes will have finished before the first Start is called. This means that code in a Start function can make use of other initializations previously carried out in the Awake phase.

GUI events

Unity has a system for rendering GUI controls over the main action in the scene and responding to clicks on these controls. This code is handled somewhat differently from the normal frame update and so it should be placed in the OnGUI function, which will be called periodically.

void OnGUI() {
	GUI.Label(labelRect, "Game Over");
}

You can also detect mouse events that occur over a GameObject as it appears in the scene. This can be used for targetting weapons or displaying information about the character currently under the mouse pointer. A set of OnMouseXXX event functions (eg, OnMouseOver, OnMouseDown) is available to allow a script to react to user actions with the mouse. For example, if the mouse button is pressed while the pointer is over a particular object then an OnMouseDown function in that object's script will be called if it exists.

Physics events

The physics engine will report collisions against an object by calling event functions on that object's script. The OnCollisionEnter, OnCollisionStay and OnCollisionExit functions will be called as contact is made, held and broken. The corresponding OnTriggerEnter, OnTriggerStay and OnTriggerExit functions will be called when the object's collider is configured as a Trigger (ie, a collider that simply detects when something enters it rather than reacting physically). These functions may be called several times in succession if more than one contact is detected during the physics update and so a parameter is passed to the function giving details of the collision (position, identity of the incoming object, etc).

void OnCollisionEnter(otherObj: Collision) {
	if (otherObj.tag == "Arrow") {
		ApplyDamage(10);
	}
}

Page last updated: 2013-03-25



CreateDestroyObjects

Some games keep a constant number of objects in the scene, but it is very common for characters, treasures and other object to be created and removed during gameplay. In Unity, a GameObject can be created using the Instantiate function which makes a new copy of an existing object:-

public GameObject enemy;

void Start() {
	for (int i = 0; i < 5; i++) {
		Instantiate(enemy);
	}
}

Note that the object from which the copy is made doesn't have to be present in the scene. It is more common to use a prefab dragged to a public variable from the Project panel in the editor. Also, instantiating a GameObject will copy all the Components present on the original.

There is also a Destroy function that will destroy an object after the frame update has finished or optionally after a short time delay:-

void OnCollisionEnter(otherObj: Collision) {
	if (otherObj == "Missile") {
		Destroy(gameObject,.5f);
	}
}

Note that the Destroy function can destroy individual components without affecting the GameObject itself. A common mistake is to write something like:-

Destroy(this);

...which will actually just destroy the script component that calls it rather than destroying the GameObject the script is attached to.

Page last updated: 2013-03-25



Coroutines

When you call a function, it runs to completion before returning. This effectively means that any action taking place in a function must happen within a single frame update; a function call can't be used to contain a procedural animation or a sequence of events over time. As an example, consider the task of gradually reducing an object's alpha (opacity) value until it becomes completely invisible.

void Fade() {
	for (float f = 1f; f >= 0; f -= 0.1f) {
		Color c = renderer.material.color;
		c.a = f;
		renderer.material.color = c;
	}
}

As it stands, the Fade function will not have the effect you might expect. In order for the fading to be visible, the alpha must be reduced over a sequence of frames to show the intermediate values being rendered. However, the function will execute in its entirety within a single frame update. The intermediate values will never be seen and the object will disappear instantly.

It is possible to handle situations like this by adding code to the Update function that executes the fade on a frame-by-frame basis. However, it is often more convenient to use a coroutine for this kind of task.

A coroutine is like a function that has the ability to pause execution and return control to Unity but then to continue where it left off on the following frame. In C#, a coroutine is declared like this:-

IEnumerator Fade() {
	for (float f = 1f; f >= 0; f -= 0.1f) {
		Color c = renderer.material.color;
		c.a = f;
		renderer.material.color = c;
		yield return;
	}
}

It is essentially a function declared with a return type of IEnumerator and with the yield return statement included somewhere in the body. The yield return line is the point at which execution will pause and be resumed the following frame. To set a coroutine running, you need to use the StartCoroutine function:-

void Update() {
	if (Input.GetKeyDown("f")) {
		StartCoroutine("Fade");
	}
}

In UnityScript, things are slightly simpler. Any function that includes the yield statement is understood to be a coroutine and the IEnumerator return type need not be explicitly declared:-

function Fade() {
	for (var f = 1.0; f >= 0; f -= 0.1) {
		var c = renderer.material.color;
		c.a = f;
		renderer.material.color = c;
		yield;
	}
}

Also, a coroutine can be started in UnityScript by calling it as if it were a normal function:-

function Update() {
	if (Input.GetKeyDown("f")) {
		Fade();
	}
}

You will notice that the loop counter in the Fade function maintains its correct value over the lifetime of the coroutine. In fact any variable or parameter will be correctly preserved between yields.

By default, a coroutine is resumed on the frame after it yields but it is also possible to introduce a time delay using WaitForSeconds:-

IEnumerator Fade() {
	for (float f = 1f; f >= 0; f -= 0.1f) {
		Color c = renderer.material.color;
		c.a = f;
		renderer.material.color = c;
		yield return new WaitForSeconds(.1f);
	}
}

...on in UnityScript

function Fade() {
	for (var f = 1.0; f >= 0; f -= 0.1) {
		var c = renderer.material.color;
		c.a = f;
		renderer.material.color = c;
		yield WaitForSeconds(0.1);
	}
}

This can be used as a way to spread an effect over a period time but it is also a useful optimization. Many tasks in a game need to be carried out periodically and the most obvious way to do this is to include them in the Update function. However, this function will typically be called many times per second. When a task doesn't need to be repeated quite so frequently, you can put it in a coroutine to get an update regularly but not every single frame. An example of this might be an alarm that warns the player if an enemy is nearby. The code might look something like this:-

function ProximityCheck() {
	for (int i = 0; i < enemies.Length; i++) {
		if (Vector3.Distance(transform.position, enemies[i].transform.position) < dangerDistance) {
				return true;
		}
	}

	return false;
}

If there are a lot of enemies then calling this function every frame might introduce a significant overhead. However, you could use a coroutine to call it every tenth of a second:-

IEnumerator DoCheck() {
	for(;;) {
		ProximityCheck;
		yield return new WaitForSeconds(.1f);
	}
}

This would greatly reduce the number of checks carried out without any noticeable effect on gameplay.

Page last updated: 2013-09-25



ScriptCompileOrderFolders

For the most part, you can choose any names you like for the folders in your project but Unity reserves some names to indicate that the contents have a special purpose. Some of these folders have an effect on the order of script compilation. Essentially, there are four separate phases of script compilation and the phase where a script will be compiled is determined by its parent folder.

This is significant in cases where a script must refer to classes defined in other scripts. The basic rule is that anything that will be compiled in a phase after the current one cannot be referenced. Anything that is compiled in the current phase or an earlier phase is fully available.

Another situation occurs when a script written in one language must refer to a class defined in another language (say, a UnityScript file that declares variables of a class defined in a C# script). The rule here is that the class being referenced must have been compiled in a earlier phase.

The phases of compilation are as follows:-

Phase 1: Runtime scripts in folders called Standard Assets, Pro Standard Assets and Plugins.

Phase 2: Editor scripts in folders called Standard Assets/Editor, Pro Standard Assets/Editor and Plugins/Editor.

Phase 3: All other scripts that are not inside a folder called Editor.

Phase 4: All remaining scripts (ie, the ones that are inside a folder called Editor).

Additionally, any script inside a folder called WebPlayerTemplates at the top level of the Assets folder will not be compiled at all. This behaviour is slightly different from the other special folder names which also work within sub-folders (eg, Scripts/Editor works as an editor script folder but Scripts/WebPlayerTemplates does not prevent compilation).

A common example is where a UnityScript file needs to reference a class defined in a C# file. You can achieve this by placing the C# file inside a Plugins folder and the UnityScript file in a non-special folder. If you don't do this, you will get an error saying the C# class cannot be found.

Page last updated: 2013-09-19



Namespaces

As projects become larger and the number of scripts increases, the likelihood of having clashes between script class names grows ever greater. This is especially true when several programmers are working on different aspects of the game separately and will eventually combine their efforts in one project. For example, one programmer may be writing the code to control the main player character while another writes the equivalent code for the enemy. Both programmers may choose to call their main script class Controller, but this will cause a clash when their projects are combined.

To some extent, this problem can be avoided by adopting a naming convention or by renaming classes whenever a clash is discovered (eg, the classes above could be given names like PlayerController and EnemyController). However, this is troublesome when there are several classes with clashing names or when variables are declared using those names - each mention of the old class name must be replaced for the code to compile.

The C# language offers a feature called namespaces that solves this problem in a robust way. A namespace is simply a collection of classes that are referred to using a chosen prefix on the class name. In the example below, the classes Controller1 and Controller2 are members of a namespace called Enemy:-

namespace Enemy {
	public class Controller1 : MonoBehaviour {
		...
	}

	public class Controller2 : MonoBehaviour {
		...
	}
}

In code, these classes are referred to as Enemy.Controller1 and Enemy.Controller2, respectively. This is better than renaming the classes insofar as the namespace declaration can be bracketed around existing class declarations (ie, it is not necessary to change the names of all the classes individually). Furthermore, you can use multiple bracketed namespace sections around classes wherever they occur, even if those classes are in different source files.

You can avoid having to type the namespace prefix repeatedly by adding a using directive at the top of the file.

using Enemy;

This line indicates that where the class names Controller1 and Controller2 are found, they should be taken to mean Enemy.Controller1 and Enemy.Controller2, respectively. If the script also needs to refer to classes with the same name from a different namespace (one called Player, say), then the prefix can still be used. If two namespaces that contain clashing class names are imported with using directives at the same time, the compiler will report an error.

Page last updated: 2013-09-03



Attributes

Attributes are markers that can be placed above a class, property or function in a script to indicate special behaviour. For example, the HideInInspector attribute can be added above a property declaration to prevent the property being shown in the inspector, even if it is public. In JavaScript, an attribute name begins with an "@" sign, whilst in C# and Boo, it is contained within square brackets:-

// JS

@HideInInspector
var strength: float;


// C#

[HideInInspector]
public float strength;

Unity provides a number of attributes which are listed in the script reference (select the Editor or Runtime Attributes section from popup menu in the sidebar). There are also attributes defined in the .NET libraries which may sometimes be useful in Unity code.

Note: the ThreadStatic attribute defined in the .NET library should not be used as it will cause a crash if added to a Unity script.

Page last updated: 2013-10-25



Asset Store

Unity's Asset Store is home to a growing library of free and commercial assets created both by Unity Technologies and also members of the community. A wide variety of assets is available, covering everything from textures, models and animations to whole project examples, tutorials and Editor extensions. The assets are accessed from a simple interface built into the Unity Editor and are downloaded and imported directly into your project.

Page last updated: 2013-07-17



AccessNavigation

You can open the Asset Store window by selecting Window->AssetStore from the main menu. On your first visit, you will be prompted to create a free user account which you will use to access the Store subsequently.


The Asset Store front page.

The Store provides a browser-like interface which allows you to navigate either by free text search or by browsing packages and categories. To the left of the main tool bar are the familiar browsing buttons for navigating through the history of viewed items:-

To the right of these are buttons for viewing the Download Manager and for viewing the current contents of your shopping cart.

The Download Manager allows you to view the packages you have already bought and also to find and install any updates. Additionally, the standard packages supplied with Unity can be viewed and added to your project with the same interface.


The Download Manager.

Location of Downloaded Asset Files

You will rarely, if ever, need to access the files downloaded from the Asset Store directly. However, if you do need to, you can find them in

  
~/Library/Unity/Asset Store

...on the Mac and in

  C:\Users\accountName\AppData\Roaming\Unity\Asset Store

...on Windows. These folders contain subfolders that correspond to particular Asset Store vendors - the actual asset files are contained in the appropriate subfolders.

Page last updated: 2013-07-17



Asset Store Publisher Administration

Setting up a Publisher account

  1. Open up the Asset Store and download the latest version of "Asset Store Tools" from the Asset Store (you'll need to sign in, if you haven't done so already).
  2. Once downloaded and imported to your project, you should see the "Asset Store Tools" menu appear in your Toolbar. Scroll down and click the Package Manager button.
  3. Now you have the Package Manager open, you can click the link in the top right-hand corner that reads "Publisher account".
  4. This will bring up a window that prompts you to create your Publisher Account. You'll need to fill out your Publisher name, Publisher URL, Publisher description (including an email Support address for your packages) and Key images.
  5. Once you're done, hit Save. Voila, all finished!

Publisher Administration

Once you have your Publisher Account for the Asset Store setup, you'll be able to log into the Publisher Administration portal, here: https://publisher.assetstore.unity3d.com/

You'll see a number of tabs. Below is a summary of each of these:

Payouts

There are three options when receiving payouts from the Asset Store.

  1. Paypal - Free transactions. No minimum transfer. Monthly transfers.
  2. Wire - $20 Transaction fee. Minimum transfer of $250. Quarterly transfers.
  3. Check (US only) - $15 Transaction fee. Minimum transfer of $250. Quarterly transfers.

Simply check the appropriate box in the Payout tab and fill out your details.

Page last updated: 2013-07-17



AssetStoreFAQ

What date will I receive my monthly or quarterly transfer?

All payouts are scheduled for the 15th of each month

Why haven't I received my payout?

Check your details are correct in the "Payout" tab in your Publisher Administration account. If everything looks correct and you still haven't received your funds, please contact: assetstore@unity3d.com

My package has shown as Pending for a while now, what should I do?

Our Vetting Team receive a huge amount of submissions per week, please be patient when waiting for acceptance. If you feel there may be an issue with your submission, please contact assetstore@unity3d.com stating your Publisher and Package details.

Can I merge my account with my co-workers' account or another additional account?

Unfortunately not, once an account has been created and purchases have been made, we cannot swap, merge or edit these purchases to appear in another account.

I can't find my answer here. Can I speak to a human about my issue?

Of course you can, drop us an email at assetstore@unity3d.com. We aim to respond within 24 hours.

Page last updated: 2013-07-17



Asset Server

Unity Asset Server Overview

The Unity Asset Server is an asset and version control system with a graphical user interface integrated into Unity. It is meant to be used by team members working together on a project on different computers either in-person or remotely. The Asset Server is highly optimized for handling large binary assets in order to cope with large multi gigabyte project folders. When uploading assets, Import Settings and other meta data about each asset is uploaded to the asset server as well. Renaming and moving files is at the core of the system and well supported.

It is available only for Unity Pro, and is an additional license per client. To purchase an Asset Server Client License, please visit the Unity store at http://unity3d.com/store

New to Source Control?

If you have never used Source Control before, it can be a little unfriendly to get started with any versioning system. Source Control works by storing an entire collection of all your assets - meshes, textures, materials, scripts, and everything else - in a database on some kind of server. That server might be your home computer, the same one that you use to run Unity. It might be a different computer in your local network. It might be a remote machine colocated in a different part of the world. It could even be a virtual machine. There are a lot of options, but the location of the server doesn't matter at all. The important thing is that you can access it somehow over your network, and that it stores your game data.

In a way, the Asset Server functions as a backup of your Project Folder. You do not directly manipulate the contents of the Asset Server while you are developing. You make changes to your Project locally, then when you are done, you Commit Changes to the Project on the Server. This makes your local Project and the Asset Server Project identical.

Now, when your fellow developers make a change, the Asset Server is identical to their Project, but not yours. To synchronize your local Project, you request to Update from Server. Now, whatever changes your team members have made will be downloaded from the server to your local Project.

This is the basic workflow for using the Asset Server. In addition to this basic functionality, the Asset Server allows for rollback to previous versions of assets, detailed file comparison, merging two different scripts, resolving conflicts, and recovering deleted assets.

Setting up the Asset Server

The Asset Server requires a one time server setup and a client configuration for each user. You can read about how to do that in the Asset Server Setup page.

The rest of this guide explains how to deploy, administrate, and regularly use the Asset Server.

Daily use of the Asset Server

This section explains the common tasks, workflow and best practices for using the Asset Server on a day-to-day basis.

Getting Started

If you are joining a team that has a lot of work stored on the Asset Server already, this is the quickest way to get up and running correctly.

  1. Create a new empty Project with no packages imported
  2. Go to Edit->Project Settings->Editor and select Asset Server as the version control mode
  3. From the menubar, select Window->Version
  4. Click the Connection button
  5. Enter your user name and password (provided by your Asset Server administrator)
  6. Click Show Projects and select the desired project
  7. Click Connect
  8. Click the Update tab
  9. Click the Update button
  10. If a conflict occurs, discard all local versions
  11. Wait for the update to complete
  12. You are ready to go

Workflow Fundamentals

When using the Asset Server with a multi-person team, it is generally good practice to Update all changed assets from the server when you begin working, and Commit your changes at the end of the day, or whenever you're done working. You should also commit changes when you have made significant progress on something, even if it is in the middle of the day. Committing your changes regularly and frequently is recommended.

Understanding the Server View

The Server View is your window into the Asset Server you're connected to. You can open the Server View by selecting Window->Version Control.


The Overview tab

The Server View is broken into tabs: Overview Update, and Commit. Overview will show you any differences between your local project and the latest version on the server with options to quickly commit local changes or download the latest updates. Update will show you the latest remote changes on the server and allow you to download them to your local project. Commit allows you to create a Changeset and commit it to the server for others to download.

Connecting to the server

Before you can use the asset server, you must connect to it. To do this you click the Connection button, which takes you to the connection screen:


The Asset Server connection screen

Here you need to fill in:

  1. Server address
  2. Username
  3. Password

By clicking Show projects you can now see the available projects on the asset server, and choose which one to connect to by clicking Connect. Note that the username and password you use can be obtain from your system administrator. Your system administrator created accounts when they installed Asset Server.

Updating from the Server

To download all updates from the server, select the Update tab from the Overview tab and you will see a list of the latest committed Changesets. By selecting one of these you can see what was changed in the project as well as the provided commit message. Click Update and you will begin downloading all Changeset updates.


The Update Tab

Committing Changes to the Server

When you have made a change to your local project and you want to store those changes on the server, you use the top Commit tab.


The Commit tab

Now you will be able to see all the local changes made to the project since your last update, and will be able to select which changes you wish to upload to the server. You can add changes to the changeset either by manually dragging them into the changeset field, or by using the buttons placed below the commit message field. Remember to type in a commit message which will help you when you compare versions or revert to an earlier version later on, both of which are discussed below.

Resolving conflicts

With multiple people working on the same collection of data, conflicts will inevitably arise. Remember, there is no need to panic! If a conflict exists, you will be presented with the Conflict Resolution dialog when updating your project.


The Conflict Resolution screen

Here, you will be informed of each individual conflict, and be presented with different options to resolve each individual conflict. For any single conflict, you can select Skip Asset (which will not download that asset from the server), Discard My Changes (which will completely overwrite your local version of the asset) or Ignore Server Changes (which will ignore the changes others made to the asset and after this update you will be able to commit your local changes over server ones) for each individual conflict. Additionally, you can select Merge for text assets like scripts to merge the server version with the local version.

Note: If you choose to discard your changes, the asset will be updated to the latest version from the server (i.e., it will incorporate other users' changes that have been made while you were working). If you want to get the asset back as it was when you started working, you should revert to the specific version that you checked out. (See Browsing revision history and reverting assets below.)

If you run into a conflict while you are committing your local changes, Unity will refuse to commit your changes and inform you that a conflict exists. To resolve the conflicts, select Update. Your local changes will not automatically be overwritten. At this point you will see the Conflict Resolution dialog, and can follow the instructions in the above paragraph.

Browsing revision history and reverting assets

The Asset Server retains all uploaded versions of an asset in its database, so you can revert your local version to an earlier version at any time. You can either select to restore the entire project or single files. To revert to an older version of an asset or a project, select the Overview tab then click Show History listed under Asset Server Actions. You will now see a list of all commits and be able to select and restore any file or all project to an older version.


The History dialog

Here, you can see the version number and added comments with each version of the asset or project. This is one reason why descriptive comments are helpful. Select any asset to see its history or Entire Project for all changes made in project. Find revision you need. You can either select whole revision or particular asset in revision. Then click Download Selected File to get your local asset replaced with a copy of the selected revision. Revert All Project will revert entire project to selected revision.

Prior to reverting, if there are any differences between your local version and the selected server version, those changes will be lost when the local version is reverted.

If you only want to abandon the changes made to the local copy, you don't have to revert. You can discard those local modifications by selecting Discard Changes in the main asset server window. This will immediately download the current version of the project from the server to your local Project.

Comparing asset versions

If you're curious to see the differences between two particular versions you can explicitly compare them. To do this, open History window, select revision and asset you want to compare and press Compare to Local Version. If you need to compare two different revisions of an asset - right click on it, in the context menu select Compare to Another Revision then find revision you want to compare to and select it.

Note: this feature requires that you have one of supported file diff/merge tools installed. Supported tools are:

Recovering deleted assets

Deleting a local asset and committing the delete to the server will in fact not delete an asset permanently. Just as any previous version of an asset can be restored through History window from the Overview tab.


The History dialog

Expand Deleted Assets item, find and select assets from the list and hit Recover, the selected assets will be downloaded and re-added to the local project. If the folder that the asset was located in before the deletion still exists, the asset will be restored to the original location, otherwise it will be added to the root of the Assets folder in the local project.

Best Practices & Common Issues

This is a compilation of best practices and solutions to problems which will help you when using the Asset Server:

  1. Backup, Backup, Backup
    • Maintain a backup of your database. It is very important to do this. In the unfortunate case that you have a hardware problem, a virus, a user error, etc you may loose all of your work. Therefore make sure you have a backup system in place. You can find lots of resources online for setting up backup systems.
  2. Stop the server before shutting the machine down
    • This can prevent "fast shutdowns" from being generated in the PostgreSQL (Asset Server) log. If this occurs the Asset Server has to do a recovery due to an improper shut down. This can take a very long time if you have a large project with many commits.
  3. Resetting you password from Console
    • You can reset your password directly from a shell, console or command line using the following command:

      psql -U unitysrv -d template1 -c"alter role admin with password 'MYPASSWORD'"
  4. Can't connect to Asset Server
    • The password may have expired. Try resetting your password.
    • Also the username is case sensitive: "Admin" != "admin". Make sure you are using the correct case.
    • Make sure the server is actually running:
      • On OS X or Linux you can type on the terminal: ps -aux
      • On Windows you can use the Task Manager.
    • Verify that the Asset Server is not running on more than one computer in your Network. You could be connecting to the wrong one.
  5. The Asset Server doesn't work in 64-bit Linux
    • The asset server can run OK on 64-bit Linux machines if you install 32-bit versions of the required packages. You can use "dpkg -i --force-architecture" to do this.
  6. Use the Asset Server logs to get more information
    • Windows:
      • \Unity\AssetServer\log
    • OS X:
      • /Library/UnityAssetServer/log
  7. "The application failed to initialize properly (0xc0000135)" in Windows XP
    • In this case Service Pack 2 is required, and you should install .NET 2.0.

Asset Server training complete

You should now be equipped with the knowledge you need to start using the Asset Server effectively. Get to it, and don't forget the good workflow fundamentals. Commit changes often, and don't be afraid of losing anything.

Page last updated: 2013-03-07



Setting up the Asset Server

Server-side Installation

The Asset Server is designed to be a simple one-time installation on a server machine. Interacting with the Asset Server is done through Unity. Unity can be installed on the server machine, but it does not need to be. It must be administrated from a Client machine, where Projects and Users can be added. Each additional client must be configured to synchronize with a Project, using a specific User credential.

You can install the Asset Server on Mac OS X 10.4 or later, Windows XP, Windows Vista and various Linux distributions including CentOS, Ubuntu and Suse Linux. Download Unity Asset Server from here.

The installer will install all necessary files, setup a database and launch the Asset Server. At the end of the process you will be asked to create an Admin password. This password is required to administer the Asset Server from within Unity. You must connect to the Asset Server as the administrator before you can create any projects or users.

Administrating the Asset Server

The Asset Server allows any number of Users to connect to a Project. The Administrator must first connect to the Server with Unity as a client and create new Projects and Users.

To access the Administrator controls, launch Unity and select Window->Asset Server, then click the Administration button.


The Administration tab

In the Server Address field, enter either the ip address or host name of the computer running the Asset Server that you want to administer. If the Asset Server is installed on your local machine, you can use "localhost" as the Server Address. Next, provide the administrator name and password. The administrator name is always "admin", and the password is what was entered when installing the Asset Server. Finally, hit the Connect button. You're now connected to the Asset Server, and can perform the initial setup.

Managing Projects and Users

Each Server can contain several Projects, and each User can have permission to one or more Projects. Projects are generally orthogonal, and unique in asset collections. It is best to think "one Project equals one game".

New Projects can be created by clicking on the Create button in the Server Administration tab.


Click Create, then enter a name for the new project

New users can be created by first selecting an existing project and then clicking on the New User button.


Creating a new user

After a user has been created in one Project, the user can be added to another project by enabling the checkbox on the left of the user name in the users list.

You can enable or disable user access for individual projects. To completely remove a project or user from the server use the Delete Project and Delete User buttons.

Firewall settings

The Unity Asset Server uses TCP port 10733. You might need to enable connections to this port in your firewall and/or router.

Advanced

The Asset Server is built using a modified version of PostgreSQL. Accessing the SQL database directly requires a bit of technical knowledge about SQL and Unix/Linux command lines. User discretion is advised.

Backing up

We have provided a command line tool to back up an asset server. The tool should be run from an administrator account on the machine running the asset server. Replace BACKUP_LOCATION with the path name you want the backup tool to place the backups:

Mac OS X
sudo /Library/UnityAssetServer/bin/as_backup BACKUP_LOCATION

Linux
sudo /opt/unity_asset_server/bin/as_backup BACKUP_LOCATION

Windows
"\Unity\AssetServer\bin\as_backup.cmd" BACKUP_LOCATION

as_backup will create a directory at BACKUP_LOCATION containing one or more files per project plus files containing information about each project and a backup of all users and their passwords.

Restoring a Backup

To restore an Asset Server backup produced with as_backup, first perform a clean installation of the Asset Server without any projects created. (The restore procedure will refuse to overwrite already existing projects with the same name.)

Then run the provided backup restoration tool, as_restore pointing it to the location of a backup created with as_backup:

Mac OS X
sudo /Library/UnityAssetServer/bin/as_restore BACKUP_LOCATION

Linux
sudo /opt/unity_asset_server/bin/as_restore BACKUP_LOCATION

Windows
"\Unity\AssetServer\bin\as_restore.cmd" BACKUP_LOCATION

Note that you can also use as_backup and as_restore to move an asset server installation from one machine to another by performing the backup on the source machine, moving the backup directory to the destination machine (or mount it through a network file share,) and then running as_restore to insert the data into the newly installed Asset Server instance. This will even work when the source and destination Asset Servers have different versions or are running on different operating systems.

Locating the database name of an Asset Server Project

To view the tables in a Project database, first you need to figure out the name of the actual database. Run this command line command on the machine hosting the Asset Server:

Mac OS X
/Library/UnityAssetServer/bin/psql -U admin -h localhost -d postgres -c 'select * from all_databases__view'

Linux
/opt/unity_asset_server/bin/psql -U admin -h localhost -d postgres -c 'select * from all_databases__view'

Windows
"\Unity\AssetServer\bin\psql.exe" -U admin -h localhost -d postgres -c "select * from all_databases__view"

This and other commands will prompt you for a password. Every time this happens, enter the admin password for the database, which was set during the installation. The result will be a table that follows this basic layout:

    databasename    |    projectname     |       description        | version 
--------------------+--------------------+--------------------------+---------
 sandbox            | Sandbox            | Created with Unity 2.0.0 | 1.0
 game               | Game               | Created with Unity 2.0.0 | 1.0
 my_game_project    | My Game Project    | Created with Unity 2.0.0 | 1.0
(3 rows)

Now you need to identify the "databasename" of the Project you want to back up. When creating a database, the default "databasename" is same as the "projectname" as shown inside Unity, but in lowercase and spaces replaced with underscores.

Note that if your server hosts multiple PostgreSQL databases on different ports you nay need to explicitly provide the port used to connect to the Asset Server database. In this case add -p 10733 to the commands given (assuming you have used the default port of 10733 for your instance.) For example:

Linux
/opt/unity_asset_server/bin/psql -U admin -h localhost -d postgres -c 'select * from all_databases__view' -p 10733

Additional SQL Functions

These and all other commands use tools from the PostgreSQL distribution. You can read more about these tools here: http://www.postgresql.org/docs/8.3/interactive/reference-client.html

Page last updated: 2013-03-06



Cache Server

Why should I be using the Cache Server?

Page last updated: 2013-03-07



Asset Cache Server

Unity has a completely automatic asset pipeline. Whenever a source asset like a .psd or an .fbx file is modified, Unity will detect the change and automatically reimport it. The imported data from the file is subsequently stored by Unity in its own internal format. The best parts about the asset pipeline are the "hot reloading" functionality and the guarantee that all your source assets are always in sync with what you see. This feature also comes at a cost. Any asset that is modified has to be reimported right away. When working in large teams, after getting latest from Source Control, you often have to wait for a long time to re-import all the assets modified or created by other team members. Also, switching your project platform back and forth between desktop and mobile will trigger a re-import of most assets.

The time it takes to import assets can be drastically reduced by caching the imported asset data on the Cache Server.

Each asset import is cached based on

If any of the above change, the asset gets reimported, otherwise it gets downloaded from the Cache Server.

When you enable the cache server in the preferences, you can even share asset imports across multiple projects.

Note that once the cache server is set up, this process is completely automatic, which means there are no additional workflow requirements. It will simply reduce the time it takes to import projects without getting in your way.

How to set up a Cache Server (user)

Setting up the Cache Server couldn't be easier. All you need to do is click Use Cache Server in the preferences and tell the local machine's Unity Editor where the Cache Server is.

This can be found in Unity->Preferences on the Mac or Edit->Preferences on the PC.

If you are hosting the Cache Server on your local machine, specify localhost for the server address. However, due to hard drive size limitations, it is recommended you host the Cache Server on separate machine.

How to set up a Cache Server (admin)

Admins need to set up the Cache Server machine that will host the cached assets.

You need to:

The Cache Server needs to be on a reliable machine with very large storage (much larger than the size of the project itself, as there will be multiple versions of imported resources stored). If the hard disk becomes full the Cache Server could perform slowly.

Installing the Cache Server as a service

The provided .sh and .cmd scripts should be set-up as a service on the server. The cache server can be safely killed and restarted at any time, since it uses atomic file operations.

Cache Server Configuration

If you simply start the Cache Server by double clicking the script, it will create a "cache" directory next to the script, and keep its data in there. The cache directory is allowed to grow to up to 50 GB. You can configure the size and the location of the data using command line options, like this:

./RunOSX.command --path ~/mycachePath --size 2000000000

--path lets you specify a cache location, and --size lets you specify the maximum cache size in bytes.

Requirements for the machine hosting the Cache Server

For best performance there must be enough RAM to hold an entire imported project folder. In addition, it is best to have a machine with a fast hard drive and fast Ethernet connection. The hard drive should also have sufficient free space. On the other hand, the Cache Server has very low CPU usage.

One of the main distinctions between the Cache Server and version control is that its cached data can always be rebuilt locally. It is simply a tool for improving performance. For this reason it doesn't make sense to use a Cache Server over the Internet. If you have a distributed team, you should place a separate cache server in each location.

The cache server should run on a Linux or Mac OS X machine. The Windows file system is not particularly well optimized for how the Asset Cache Server stores data and problems with file locking on Windows can cause issues that don't occur on Linux or Mac OS X.

See also Cache Server FAQ.

Page last updated: 2013-03-06



Cache Server FAQ

Will the size of my Cache Server database grow indefinitely as more and more resources get imported and stored?

The Cache Server removes assets that have not been used for a period of time automatically (of course if those assets are needed again, they will be re-created during next usage).

Does the cache server work only with the asset server?

The cache server is designed to be transparent to source/version control systems and so you are not restricted to using Unity's asset server.

What changes will cause the imported file to get regenerated?

When Unity is about to import an asset, it generates an MD5 hash of all source data.

For a texture this consists of:

If that hash is different from what is stored on the Cache Server, the asset will be reimported, otherwise the cached version will be downloaded. The client Unity editor will only pull assets from the server as they are needed - assets don't get pushed to each project as they change.

How do I work with Asset dependencies?

The Cache Server does not handle dependencies. Unity's asset pipeline does not deal with the concept of dependencies. It is built in such a way as to avoid dependencies between assets. AssetPostprocessors are a common technique used to customize the Asset importer to fit your needs. For example, you might want to add MeshColliders to some GameObjects in an fbx file based on their name or tag.

It is also easy to use AssetPostprocessors to introduce dependencies. For example you might use data from a text file next to the asset to add additional components to the imported game objects. This is not supported in the Cache Server. If you want to use the Cache Server, you will have to remove dependency on other assets in the project folder. Since the Cache Server doesn't know anything about the dependency in your postprocessor, it will not know that anything has changed thus use an old cached version of the asset.

In practice there are plenty of ways you can do asset postprocessing to work well with the cache server. You can use:

Are there any issues when working with materials?

Modifying materials that already exist might cause trouble. When using the Cache Server, Unity validates that the references to materials are maintained. But since no postprocessing calls will be invoked, the contents of the material can not be changed when a model is imported through the Cache Server. Thus you might get different results when importing with or without Cache Server. It is best to never modify materials that already exist on disk.

Are there any asset types which will not be cached by the server?

There are a few kinds of asset data which the server doesn't cache. There isn't really anything to be gained by caching script files and so the server will ignore them. Also, native files used by 3D modelling software (Maya, 3D Max, etc) are converted to FBX using the application itself. Currently, the asset server caches neither the native file nor the intermediate FBX file generated in the import process. However, it is possible to benefit from the server by exporting files as FBX from the modelling software and adding those to the Unity project.

See also Asset Cache Server.

Page last updated: 2013-03-06



Behind the Scenes

Unity automatically imports assets and manages various kinds of additional data about them for you. Below is a description of how this process works.

When you place an Asset such as a texture in the Assets folder, Unity will first detect that a new file has been added (the editor frequently checks the contents of the Assets folder against the list of assets it already knows about). Once a unique ID value has been assigned to the asset to enable it to be accessed internally, it will be imported and processed. The asset that you actually see in the Project panel is the result of that processing and its data contents will typically be different to those of the original asset. For example, a texture may be present in the Assets folder as a PNG file but will be converted to an internal format after import and processing.

Using an internal format for assets allows Unity to keep additional data known as metadata which enables the asset data to be handled in a much more flexible way. For example, the Photoshop file format is convenient to work with, but you wouldn't expect it to support game engine features such as mip maps. Unity's internal format, however, can add extra functionality like this to any asset type. All metadata for assets is stored in the Library folder. As as user, you should never have to alter the Library folder manually and attempting to do so may corrupt the project.

Unity allows you to create folders in the Project view to help you organize assets, and those folders will be mirrored in the actual filesystem. However, you must move the files within Unity by dragging and dropping in the Project view. If you attempt to use the filesystem/desktop to move the files then Unity will misinterpret the change (it will appear that the old asset has been deleted and a new one created in its place). This will lose information, such as links between assets and scripts in the project.

When backing up a project, you should always back up the main Unity project folder, containing both the Assets and Library folders. All the information in the subfolders is crucial to the way Unity works.

Page last updated: 2011-11-15



Creating Gameplay

Unity empowers game designers to make games. What's really special about Unity is that you don't need years of experience with code or a degree in art to make fun games. There are a handful of basic workflow concepts needed to learn Unity. Once understood, you will find yourself making games in no time. With the time you will save getting your games up and running, you will have that much more time to refine, balance, and tweak your game to perfection.

This section will explain the core concepts you need to know for creating unique, amazing, and fun gameplay. The majority of these concepts require you to write Scripts. For an overview of creating and working with Scripts, see the Scripting section.

Page last updated: 2013-11-08



Instantiating Prefabs

By this point you should understand the concept of Prefabs at a fundamental level. They are a collection of predefined GameObjects & Components that are re-usable throughout your game. If you don't know what a Prefab is, we recommend you read the Prefabs page for a more basic introduction.

Prefabs come in very handy when you want to instantiate complicated GameObjects at runtime. The alternative to instantiating Prefabs is to create GameObjects from scratch using code. Instantiating Prefabs has many advantages over the alternative approach:

Common Scenarios

To illustrate the strength of Prefabs, let's consider some basic situations where they would come in handy:

  1. Building a wall out of a single "brick" Prefab by creating it several times in different positions.
  2. A rocket launcher instantiates a flying rocket Prefab when fired. The Prefab contains a Mesh, Rigidbody, Collider, and a child GameObject with its own trail Particle System.
  3. A robot exploding to many pieces. The complete, operational robot is destroyed and replaced with a wrecked robot Prefab. This Prefab would consist of the robot split into many parts, all set up with Rigidbodies and Particle Systems of their own. This technique allows you to blow up a robot into many pieces, with just one line of code, replacing one object with a Prefab.

Building a wall

This explanation will illustrate the advantages of using a Prefab vs creating objects from code.

First, lets build a brick wall from code:

// JavaScript
function Start () {
    for (var y = 0; y < 5; y++) {
        for (var x = 0; x < 5; x++) {
            var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.AddComponent(Rigidbody);
            cube.transform.position = Vector3 (x, y, 0);
        }
    }
}


// C#
public class Instantiation : MonoBehaviour {

	void Start() {
		for (int y = 0; y < 5; y++) {
			for (int x = 0; x < 5; x++) {
				GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
				cube.AddComponent<Rigidbody>();
				cube.transform.position = new Vector3(x, y, 0);
			}
		}
	}
}

If you execute that code, you will see an entire brick wall is created when you enter Play Mode. There are two lines relevant to the functionality of each individual brick: the CreatePrimitive() line, and the AddComponent() line. Not so bad right now, but each of our bricks is un-textured. Every additional action to want to perform on the brick, like changing the texture, the friction, or the Rigidbody mass, is an extra line.

If you create a Prefab and perform all your setup before-hand, you use one line of code to perform the creation and setup of each brick. This relieves you from maintaining and changing a lot of code when you decide you want to make changes. With a Prefab, you just make your changes and Play. No code alterations required.

If you're using a Prefab for each individual brick, this is the code you need to create the wall.

// JavaScript

var brick : Transform;
function Start () {
    for (var y = 0; y < 5; y++) {
        for (var x = 0; x < 5; x++) {
            Instantiate(brick, Vector3 (x, y, 0), Quaternion.identity);
        }
    }
}


// C#
public Transform brick;

void Start() {
	for (int y = 0; y < 5; y++) {
		for (int x = 0; x < 5; x++) {
			Instantiate(brick, new Vector3(x, y, 0), Quaternion.identity);
		}
	}
}

This is not only very clean but also very reusable. There is nothing saying we are instantiating a cube or that it must contain a rigidbody. All of this is defined in the Prefab and can be quickly created in the Editor.

Now we only need to create the Prefab, which we do in the Editor. Here's how:

  1. Choose GameObject->Create Other->Cube
  2. Choose Component->Physics->Rigidbody
  3. Choose Assets->Create->Prefab
  4. In the Project View, change the name of your new Prefab to "Brick"
  5. Drag the cube you created in the Hierarchy onto the "Brick" Prefab in the Project View
  6. With the Prefab created, you can safely delete the Cube from the Hierarchy (Delete on Windows, Command-Backspace on Mac)

We've created our Brick Prefab, so now we have to attach it to the brick variable in our script. Select the empty GameObject that contains the script. Notice that a new variable has appeared in the Inspector, called "brick".


This variable can accept any GameObject or Prefab

Now drag the "Brick" Prefab from the Project View onto the brick variable in the Inspector. Press Play and you'll see the wall built using the Prefab.

This is a workflow pattern that can be used over and over again in Unity. In the beginning you might wonder why this is so much better, because the script creating the cube from code is only 2 lines longer.

But because you are using a Prefab now, you can adjust the Prefab in seconds. Want to change the mass of all those instances? Adjust the Rigidbody in the Prefab only once. Want to use a different Material for all the instances? Drag the Material onto the Prefab only once. Want to change friction? Use a different Physic Material in the Prefab's collider. Want to add a Particle System to all those boxes? Add a child to the Prefab only once.

Instantiating rockets & explosions

Here's how Prefabs fit into this scenario:

  1. A rocket launcher instantiates a rocket Prefab when the user presses fire. The Prefab contains a mesh, Rigidbody, Collider, and a child GameObject that contains a trail particle system.
  2. The rocket impacts and instantiates an explosion Prefab. The explosion Prefab contains a Particle System, a light that fades out over time, and a script that applies damage to surrounding GameObjects.

While it would be possible to build a rocket GameObject completely from code, adding Components manually and setting properties, it is far easier to instantiate a Prefab. You can instantiate the rocket in just one line of code, no matter how complex the rocket's Prefab is. After instantiating the Prefab you can also modify any properties of the instantiated object (e.g. you can set the velocity of the rocket's Rigidbody).

Aside from being easier to use, you can update the prefab later on. So if you are building a rocket, you don't immediately have to add a Particle trail to it. You can do that later. As soon as you add the trail as a child GameObject to the Prefab, all your instantiated rockets will have particle trails. And lastly, you can quickly tweak the properties of the rocket Prefab in the Inspector, making it far easier to fine-tune your game.

This script shows how to launch a rocket using the Instantiate() function.

// JavaScript

// Require the rocket to be a rigidbody.
// This way we the user can not assign a prefab without rigidbody
var rocket : Rigidbody;
var speed = 10.0;

function FireRocket () {
    var rocketClone : Rigidbody = Instantiate(rocket, transform.position, transform.rotation);
    rocketClone.velocity = transform.forward * speed;
    // You can also acccess other components / scripts of the clone
    rocketClone.GetComponent(MyRocketScript).DoSomething();
}

// Calls the fire method when holding down ctrl or mouse
function Update () {
    if (Input.GetButtonDown("Fire1")) {
        FireRocket();
    }
}


// C#

// Require the rocket to be a rigidbody.
// This way we the user can not assign a prefab without rigidbody
public Rigidbody rocket;
public float speed = 10f;

void FireRocket () {
	Rigidbody rocketClone = (Rigidbody) Instantiate(rocket, transform.position, transform.rotation);
	rocketClone.velocity = transform.forward * speed;

	// You can also acccess other components / scripts of the clone
	rocketClone.GetComponent<MyRocketScript>().DoSomething();
}

// Calls the fire method when holding down ctrl or mouse
void Update () {
	if (Input.GetButtonDown("Fire1")) {
		FireRocket();
	}
}

Replacing a character with a ragdoll or wreck

Let's say you have a fully rigged enemy character and he dies. You could simply play a death animation on the character and disable all scripts that usually handle the enemy logic. You probably have to take care of removing several scripts, adding some custom logic to make sure that no one will continue attacking the dead enemy anymore, and other cleanup tasks.

A far better approach is to immediately delete the entire character and replace it with an instantiated wrecked prefab. This gives you a lot of flexibility. You could use a different material for the dead character, attach completely different scripts, spawn a Prefab containing the object broken into many pieces to simulate a shattered enemy, or simply instantiate a Prefab containing a version of the character.

Any of these options can be achieved with a single call to Instantiate(), you just have to hook it up to the right prefab and you're set!

The important part to remember is that the wreck which you Instantiate() can be made of completely different objects than the original. For example, if you have an airplane, you would model two versions. One where the plane consists of a single GameObject with Mesh Renderer and scripts for airplane physics. By keeping the model in just one GameObject, your game will run faster since you will be able to make the model with less triangles and since it consists of fewer objects it will render faster than using many small parts. Also while your plane is happily flying around there is no reason to have it in separate parts.

To build a wrecked airplane Prefab, the typical steps are:

  1. Model your airplane with lots of different parts in your favorite modeler
  2. Create an empty Scene
  3. Drag the model into the empty Scene
  4. Add Rigidbodies to all parts, by selecting all the parts and choosing Component->Physics->Rigidbody
  5. Add Box Colliders to all parts by selecting all the parts and choosing Component->Physics->Box Collider
  6. For an extra special effect, add a smoke-like Particle System as a child GameObject to each of the parts
  7. Now you have an airplane with multiple exploded parts, they fall to the ground by physics and will create a Particle trail due to the attached particle system. Hit Play to preview how your model reacts and do any necessary tweaks.
  8. Choose Assets->Create Prefab
  9. Drag the root GameObject containing all the airplane parts into the Prefab

The following example shows how these steps are modelled in code.

// JavaScript

var wreck : GameObject;

// As an example, we turn the game object into a wreck after 3 seconds automatically
function Start () {
    yield WaitForSeconds(3);
    KillSelf();
}

// Calls the fire method when holding down ctrl or mouse
function KillSelf () {
    // Instantiate the wreck game object at the same position we are at
    var wreckClone = Instantiate(wreck, transform.position, transform.rotation);

    // Sometimes we need to carry over some variables from this object
    // to the wreck
    wreckClone.GetComponent(MyScript).someVariable = GetComponent(MyScript).someVariable;

    // Kill ourselves
    Destroy(gameObject);


// C#

public GameObject wreck;

// As an example, we turn the game object into a wreck after 3 seconds automatically
IEnumerator Start() {
	yield return new WaitForSeconds(3);
	KillSelf();
}

// Calls the fire method when holding down ctrl or mouse
void KillSelf () {
	// Instantiate the wreck game object at the same position we are at
	GameObject wreckClone = (GameObject) Instantiate(wreck, transform.position, transform.rotation);

	// Sometimes we need to carry over some variables from this object
	// to the wreck
	wreckClone.GetComponent<MyScript>().someVariable = GetComponent<MyScript>().someVariable;

	// Kill ourselves
	Destroy(gameObject);
}

} 

Placing a bunch of objects in a specific pattern

Lets say you want to place a bunch of objects in a grid or circle pattern. Traditionally this would be done by either:

  1. Building an object completely from code. This is tedious! Entering values from a script is both slow, unintuitive and not worth the hassle.
  2. Make the fully rigged object, duplicate it and place it multiple times in the scene. This is tedious, and placing objects accurately in a grid is hard.

So use Instantiate() with a Prefab instead! We think you get the idea of why Prefabs are so useful in these scenarios. Here's the code necessary for these scenarios:

// JavaScript

// Instantiates a prefab in a circle

var prefab : GameObject;
var numberOfObjects = 20;
var radius = 5;

function Start () {
    for (var i = 0; i < numberOfObjects; i++) {
        var angle = i * Mathf.PI * 2 / numberOfObjects;
        var pos = Vector3 (Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
        Instantiate(prefab, pos, Quaternion.identity);
    }
}


// C#
// Instantiates a prefab in a circle

public GameObject prefab;
public int numberOfObjects = 20;
public float radius = 5f;

void Start() {
	for (int i = 0; i < numberOfObjects; i++) {
		float angle = i * Mathf.PI * 2 / numberOfObjects;
		Vector3 pos = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
		Instantiate(prefab, pos, Quaternion.identity);
	}
}
// JavaScript

// Instantiates a prefab in a grid

var prefab : GameObject;
var gridX = 5;
var gridY = 5;
var spacing = 2.0;

function Start () {
    for (var y = 0; y < gridY; y++) {
        for (var x=0;x<gridX;x++) {
            var pos = Vector3 (x, 0, y) * spacing;
            Instantiate(prefab, pos, Quaternion.identity);
        }
    }
}


// C#

// Instantiates a prefab in a grid

public GameObject prefab;
public float gridX = 5f;
public float gridY = 5f;
public float spacing = 2f;

void Start() {
	for (int y = 0; y < gridY; y++) {
		for (int x = 0; x < gridX; x++) {
			Vector3 pos = new Vector3(x, 0, y) * spacing;
			Instantiate(prefab, pos, Quaternion.identity);
		}
	}
} 

Page last updated: 2013-07-31



Input

Desktop

Unity supports keyboard, joystick and gamepad input.

Virtual axes and buttons can be created in the Input Manager, and end users can configure Keyboard input in a nice screen configuration dialog.

You can setup joysticks, gamepads, keyboard, and mouse, then access them all through one simple scripting interface.

From scripts, all virtual axes are accessed by their name.

Every project has the following default input axes when it's created:

  • Horizontal and Vertical are mapped to w, a, s, d and the arrow keys.
  • Fire1, Fire2, Fire3 are mapped to Control, Option (Alt), and Command, respectively.
  • Mouse X and Mouse Y are mapped to the delta of mouse movement.
  • Window Shake X and Window Shake Y is mapped to the movement of the window.

Adding new Input Axes

If you want to add new virtual axes go to the Edit->Project Settings->Input menu. Here you can also change the settings of each axis.

You map each axis to two buttons on a joystick, mouse, or keyboard keys.

NameThe name of the string used to check this axis from a script.
Descriptive NamePositive value name displayed in the input tab of the Configuration dialog for standalone builds.
Descriptive Negative NameNegative value name displayed in the Input tab of the Configuration dialog for standalone builds.
Negative ButtonThe button used to push the axis in the negative direction.
Positive ButtonThe button used to push the axis in the positive direction.
Alt Negative ButtonAlternative button used to push the axis in the negative direction.
Alt Positive ButtonAlternative button used to push the axis in the positive direction.
GravitySpeed in units per second that the axis falls toward neutral when no buttons are pressed.
DeadSize of the analog dead zone. All analog device values within this range result map to neutral.
SensitivitySpeed in units per second that the the axis will move toward the target value. This is for digital devices only.
SnapIf enabled, the axis value will reset to zero when pressing a button of the opposite direction.
InvertIf enabled, the Negative Buttons provide a positive value, and vice-versa.
TypeThe type of inputs that will control this axis.
AxisThe axis of a connected device that will control this axis.
Joy NumThe connected Joystick that will control this axis.

Use these settings to fine tune the look and feel of input. They are all documented with tooltips in the Editor as well.

Using Input Axes from Scripts

You can query the current state from a script like this:

value = Input.GetAxis ("Horizontal");

An axis has a value between -1 and 1. The neutral position is 0. This is the case for joystick input and keyboard input.

However, Mouse Delta and Window Shake Delta are how much the mouse or window moved during the last frame. This means it can be larger than 1 or smaller than -1 when the user moves the mouse quickly.

It is possible to create multiple axes with the same name. When getting the input axis, the axis with the largest absolute value will be returned. This makes it possible to assign more than one input device to one axis name. For example, create one axis for keyboard input and one axis for joystick input with the same name. If the user is using the joystick, input will come from the joystick, otherwise input will come from the keyboard. This way you don't have to consider where the input comes from when writing scripts.

Button Names

To map a key to an axis, you have to enter the key's name in the Positive Button or Negative Button property in the Inspector.

The names of keys follow this convention:

  • Normal keys: "a", "b", "c" ...
  • Number keys: "1", "2", "3", ...
  • Arrow keys: "up", "down", "left", "right"
  • Keypad keys: "[1]", "[2]", "[3]", "[+]", "[equals]"
  • Modifier keys: "right shift", "left shift", "right ctrl", "left ctrl", "right alt", "left alt", "right cmd", "left cmd"
  • Mouse Buttons: "mouse 0", "mouse 1", "mouse 2", ...
  • Joystick Buttons (from any joystick): "joystick button 0", "joystick button 1", "joystick button 2", ...
  • Joystick Buttons (from a specific joystick): "joystick 1 button 0", "joystick 1 button 1", "joystick 2 button 0", ...
  • Special keys: "backspace", "tab", "return", "escape", "space", "delete", "enter", "insert", "home", "end", "page up", "page down"
  • Function keys: "f1", "f2", "f3", ...

The names used to identify the keys are the same in the scripting interface and the Inspector.

value = Input.GetKey ("a");

Mobile Input

On iOS and Android, the Input class offers access to touchscreen, accelerometer and geographical/location input.

Access to keyboard on mobile devices is provided via the iOS keyboard.

Multi-Touch Screen

The iPhone and iPod Touch devices are capable of tracking up to five fingers touching the screen simultaneously. You can retrieve the status of each finger touching the screen during the last frame by accessing the Input.touches property array.

Android devices don't have a unified limit on how many fingers they track. Instead, it varies from device to device and can be anything from two-touch on older devices to five fingers on some newer devices.

Each finger touch is represented by an Input.Touch data structure:

fingerIdThe unique index for a touch.
positionThe screen position of the touch.
deltaPositionThe screen position change since the last frame.
deltaTimeAmount of time that has passed since the last state change.
tapCountThe iPhone/iPad screen is able to distinguish quick finger taps by the user. This counter will let you know how many times the user has tapped the screen without moving a finger to the sides. Android devices do not count number of taps, this field is always 1.
phaseDescribes so called "phase" or the state of the touch. It can help you determine if the touch just began, if user moved the finger or if he just lifted the finger.

Phase can be one of the following:

BeganA finger just touched the screen.
MovedA finger moved on the screen.
StationaryA finger is touching the screen but hasn't moved since the last frame.
EndedA finger was lifted from the screen. This is the final phase of a touch.
CanceledThe system cancelled tracking for the touch, as when (for example) the user puts the device to her face or more than five touches happened simultaneously. This is the final phase of a touch.

Following is an example script which will shoot a ray whenever the user taps on the screen:

var particle : GameObject;
function Update () {
	for (var touch : Touch in Input.touches) {
		if (touch.phase == TouchPhase.Began) {
			// Construct a ray from the current touch coordinates
			var ray = Camera.main.ScreenPointToRay (touch.position);
			if (Physics.Raycast (ray)) {
				// Create a particle if hit
				Instantiate (particle, transform.position, transform.rotation);
			}
		}
	}
}

Mouse Simulation

On top of native touch support Unity iOS/Android provides a mouse simulation. You can use mouse functionality from the standard Input class.

Accelerometer

As the mobile device moves, a built-in accelerometer reports linear acceleration changes along the three primary axes in three-dimensional space. Acceleration along each axis is reported directly by the hardware as G-force values. A value of 1.0 represents a load of about +1g along a given axis while a value of -1.0 represents -1g. If you hold the device upright (with the home button at the bottom) in front of you, the X axis is positive along the right, the Y axis is positive directly up, and the Z axis is positive pointing toward you.

You can retrieve the accelerometer value by accessing the Input.acceleration property.

The following is an example script which will move an object using the accelerometer:

var speed = 10.0;
function Update () {
	var dir : Vector3 = Vector3.zero;

	// we assume that the device is held parallel to the ground
	// and the Home button is in the right hand

	// remap the device acceleration axis to game coordinates:
	//  1) XY plane of the device is mapped onto XZ plane
	//  2) rotated 90 degrees around Y axis
	dir.x = -Input.acceleration.y;
	dir.z = Input.acceleration.x;

	// clamp acceleration vector to the unit sphere
	if (dir.sqrMagnitude > 1)
		dir.Normalize();

	// Make it move 10 meters per second instead of 10 meters per frame...
	dir *= Time.deltaTime;

	// Move object
	transform.Translate (dir * speed);
}

Low-Pass Filter

Accelerometer readings can be jerky and noisy. Applying low-pass filtering on the signal allows you to smooth it and get rid of high frequency noise.

The following script shows you how to apply low-pass filtering to accelerometer readings:

var AccelerometerUpdateInterval : float = 1.0 / 60.0;
var LowPassKernelWidthInSeconds : float = 1.0;

private var LowPassFilterFactor : float = AccelerometerUpdateInterval / LowPassKernelWidthInSeconds; // tweakable
private var lowPassValue : Vector3 = Vector3.zero;
function Start () {
	lowPassValue = Input.acceleration;
}

function LowPassFilterAccelerometer() : Vector3 {
	lowPassValue = Mathf.Lerp(lowPassValue, Input.acceleration, LowPassFilterFactor);
	return lowPassValue;
}

The greater the value of LowPassKernelWidthInSeconds, the slower the filtered value will converge towards the current input sample (and vice versa).

I'd like as much precision as possible when reading the accelerometer. What should I do?

Reading the Input.acceleration variable does not equal sampling the hardware. Put simply, Unity samples the hardware at a frequency of 60Hz and stores the result into the variable. In reality, things are a little bit more complicated -- accelerometer sampling doesn't occur at consistent time intervals, if under significant CPU loads. As a result, the system might report 2 samples during one frame, then 1 sample during the next frame.

You can access all measurements executed by accelerometer during the frame. The following code will illustrate a simple average of all the accelerometer events that were collected within the last frame:

var period : float = 0.0;
var acc : Vector3 = Vector3.zero;
for (var evnt : iPhoneAccelerationEvent  in iPhoneInput.accelerationEvents) {
	acc += evnt.acceleration * evnt.deltaTime;
	period += evnt.deltaTime;
}
if (period > 0)
	acc *= 1.0/period;
return acc;

iOS Game Controller support

Starting with OS 7, a standardized Game Controller Input API is provided by Apple. Unity support for this API comes as part of the standard Unity Input API.

Detecting attached Game Controllers

Calling Input.GetJoystickNames will enumerate the names of all attached controllers. Names follow the pattern: "[$profile_type,$connection_type] joystick $number by $model". $profile_type might be either "basic" or "extended", $connection_type is either "wired" or "wireless". It could be used to detect the kind of connected controller. It is worth re-checking this list every few seconds to detect if controllers have been attached or detached. Here’s an example how of to do it in C#:

    private bool connected = false;
    IEnumerator CheckForControllers()
    {
        while(true)
        {
            var controllers = Input.GetJoystickNames();
            if (!connected && controllers.Length > 0)
            {
                connected = true;
                Debug.Log("Connected");
            }
            else if (connected && controllers.Length == 0)
            {
                connected = false;
                Debug.Log("Disconnected");
            }
            yield return new WaitForSeconds(1f);
        }
    }
    void Awake()
    {
        StartCoroutine(CheckForControllers());
    }

When controllers are detected you can either hide on-screen touch controls or amend them to supplement controller input. The next task is to check for Game Controller input.

Handling input

Actual input scheme is highly dependent on the type of game you are developing. But in any case it goes down to reading axes and button states. Let's take following 2D game stage as simple example:

The player controls the bean character, which can move right or left, jump and fire at the bad guys. By default, the Unity Input "Horizontal" axis is mapped to basic profile game controller dpad and the left analog stick on extended profile controllers. So the code used to move the character back and forth is pretty simple:

    float h = Input.GetAxis("Horizontal");
    if(h * rigidbody2D.velocity.x < maxSpeed)
        rigidbody2D.AddForce(Vector2.right * h * moveForce);

You can set up jump and fire actions in Unity's Input Manager. Access it from the Unity editor menu as follows: Edit > Project Settings > Input. Lets pick joystick button "A" for the "Jump" action and "X" for "Fire". Open the following actions in the Unity Input Manager and specify "joystick button 14" for "Jump" and "joystick button 15" for "Fire".

The code handling them looks like this:

    if(Input.GetButtonDown("Jump") && grounded)
    {    
        rigidbody2D.AddForce(new Vector2(0f, jumpForce));
    }
    if(Input.GetButtonDown("Fire"))
    {
        Rigidbody2D bulletInstance = Instantiate(rocket, transform.position, Quaternion.Euler(new Vector3(0,0,0))) as Rigidbody2D;
        bulletInstance.velocity = new Vector2(speed, 0);
    }

The following cheatsheet should help you map controller input in the Unity Input Manager:

NameKeyCodeAxis
Ajoystick button 14N/A
Bjoystick button 13N/A
Xjoystick button 15N/A
Yjoystick button 12N/A
Left StickN/AAxis 1 (X) - Horizontal, Axis 2 (Y) - Vertical
Right StickN/AAxis 3 - Horizontal, Axis 4 - Vertical
Dpadjoystick button 4 .. joystick button 7Basic profile only: Axis 1 (X) - Horizontal, Axis 2 (Y) - Vertical
Pausejoystick button 0N/A
L1/R1joystick button 8/joystick button 9N/A
L2/R2joystick button 10/joystick button 11N/A

Final notes on Game Controller API support

The Game Controller framework is loaded dynamically by Unity iOS runtime only if it is available. For older iOS versions it will just return an empty list of controllers.

Apple documentation explicitly states that controller input must be optional and your game should be playable without them.

Page last updated: 2013-11-26



Transforms

Transforms are a key Component in every GameObject. They dictate where the GameObject is positioned, how it is rotated, and its scale. It is impossible to have a GameObject without a Transform. You can adjust the Transform of any GameObject from the Scene View, the Inspector, or through Scripting.

The remainder of this page's text is from the Transform Component Reference page.

Transform

The Transform component determines the Position, Rotation, and Scale of each object in the scene. Every object has a Transform.


The Transform Component is editable in the Scene View and in the Inspector

Properties

PositionPosition of the Transform in X, Y, and Z coordinates.
RotationRotation of the Transform around the X, Y, and Z axes, measured in degrees.
ScaleScale of the Transform along X, Y, and Z axes. Value "1" is the original size (size at which the object was imported).

All properties of a Transform are measured relative to the Transform's parent (see below for further details). If the Transform has no parent, the properties are measured relative to World Space.

Using Transforms

Transforms are always manipulated in 3D space in the X, Y, and Z axes. In Unity, these axes are represented by the colors red, green, and blue respectively. Remember: XYZ = RGB.


Color-coded relationship between the three axes and Transform properties

Transforms can be directly manipulated in the Scene View or by editing properties in the Inspector. In the scene, you can modify Transforms using the Move, Rotate and Scale tools. These tools are located in the upper left-hand corner of the Unity Editor.


The View, Translate, Rotate, and Scale tools

The tools can be used on any object in the scene. When you click on an object, you will see the tool gizmo appear within it. The appearance of the gizmo depends on which tool is selected.



All three Gizmos can be directly edited in the Scene View.

When you click and drag on one of the three gizmo axes, you will notice that its color changes. As you drag the mouse, you will see the object translate, rotate, or scale along the selected axis. When you release the mouse button, the axis remains selected.


Any individual axis will become selected when you click on it

Around the centre of the Transform gizmo are three coloured squares. These allow you to drag the Transform in a single plane (ie, the object will move in two axes but be held still in the third axis).


Dragging in the XZ plane

Parenting

Parenting is one of the most important concepts to understand when using Unity. When a GameObject is a Parent of another GameObject, the Child GameObject will move, rotate, and scale exactly as its Parent does. Just like your arms are attached to your body, when you turn your body, your arms move because they're attached. Any object can have multiple children, but only one parent.

You can create a Parent by dragging any GameObject in the Hierarchy View onto another. This will create a Parent-Child relationship between the two GameObjects.


Example of a Parent-Child hierarchy. GameObjects with foldout arrows to the left of their names are parents.

In the above example, we say that the arms are parented to the body and the hands are parented to the arms. The scenes you make in Unity will contain collections of these Transform hierarchies. The topmost parent object is called the Root object. When you move, scale or rotate a parent, all the changes in its Transform are applied to its children as well.

It is worth pointing out that the Transform values in the Inspector of any Child GameObject are displayed relative to the Parent's Transform values. These are also called the Local Coordinates. Through scripting, you can access the Global Coordinates as well as the local coordinates.

You can build compound objects by parenting several separate objects together, for example, the skeletal structure of a human ragdoll. You can also achieve useful effects with simple hierarchies. For example, if you have a horror game that takes place at night, you can create an effective atmosphere with a flashlight. To create this object, you would parent a spotlight Transform to the flashlight Transform. Then, any alteration of the flashlight Transform will affect the spotlight, creating a convincing flashlight effect.

Performance Issues and Limitations with Non-Uniform Scaling

Non-uniform scaling is when the Scale in a Transform has different values for x, y, and z; for example (2, 4, 2). In contrast, uniform scaling has the same value for x, y, and z; for example (3, 3, 3). Non-uniform scaling can be useful in a few select cases but should be avoided whenever possible.

Non-uniform scaling has a negative impact on rendering performance. In order to transform vertex normals correctly, we transform the mesh on the CPU and create an extra copy of the data. Normally we can keep the mesh shared between instances in graphics memory, but in this case you pay both a CPU and memory cost per instance.

There are also certain limitations in how Unity handles non-uniform scaling:

Importance of Scale

The scale of the Transform determines the difference between the size of your mesh in your modeling application and the size of your mesh in Unity. The mesh's size in Unity (and therefore the Transform's scale) is very important, especially during physics simulation. There are three factors that can affect the scale of your object:

Ideally, you should not adjust the Scale of your object in the Transform Component. The best option is to create your models at real-life scale so you won't have to change your Transform's scale. The next best option is to adjust the scale at which your mesh is imported in the Import Settings for your individual mesh. Certain optimizations occur based on the import size, and instantiating an object that has an adjusted scale value can decrease performance. For more information, see the section about optimizing scale on the Rigidbody component reference page.

Hints

Page last updated: 2007-11-16



Physics

To have convincing physical behaviour, an object in a game must accelerate correctly and be affected by collisions, gravity and other forces. Unity's built-in physics engines provide components that handle the physical simulation for you. With just a few parameter settings, you can create objects that behave passively in a realistic way (ie, they will be moved by collisions and falls but will not start moving by themselves). By controlling the physics from scripts, you can give an object the dynamics of a vehicle, a machine or even a moving piece of cloth. This page gives an overview of the main physics components in Unity with links for further reading.

Note: there are actually two separate physics engines in Unity, one for 3D physics and one for 2D physics. The main concepts are identical between the two engines (except for the extra dimension in 3D) but they are implemented with different components. So for example, there is Rigidbody component for 3D physics and an analogous Rigidbody 2D for 2D physics.

Rigidbodies

A Rigidbody is the main component that enables physical behaviour for an object. With a Rigidbody attached, the object will immediately respond to gravity. If one or more Collider components are also added then the object will be moved by incoming collisions.

Since a Rigidbody component takes over the movement of the object it is attached to, you shouldn't try to move it from a script by changing the Transform properties such as position and rotation. Instead, you should apply forces to push the object and let the physics engine calculate the results.

There are some cases where you might want an object to have a Rigidbody without having its motion controlled by the physics engine. For example, you may want to control your character directly from script code but still allow it to be detected by triggers (see Triggers below). This kind of non-physical motion produced from a script is known as kinematic motion. The Rigidbody component has a property called Is Kinematic which will remove it from the control of the physics engine and allow it to be moved kinematically from a script. It is possible to change the value of Is Kinematic from a script to allow physics to be switched on and off for an object, but this comes with a performance overhead and should be used sparingly.

See the Rigidbody and Rigidbody 2D reference pages for further details about the settings and scripting options for these components.

Colliders

Collider components define the shape of an object for the purposes of physical collisions. A collider, which is invisible, need not be the exact same shape as the object's mesh and in fact, a rough approximation is often more efficient and indistinguishable in gameplay. The simplest (and least processor-intensive) colliders and the so-called primitive collider types. In 3D, these are the Box Collider, Sphere Collider and Capsule Collider. In 2D, you can use the Box Collider 2D and Circle Collider 2D. Any number of these can be added to a single object to create compound colliders. With careful positioning and sizing, compound colliders can often approximate the shape of an object quite well while keeping a low processor overhead. Further flexibility can be gained by having additional colliders on child objects (eg, boxes can be rotated relative to the local axes of the parent object). However, you should be sure that there is only one Rigidbody and this should be placed on the root object in the hierarchy.

There are some cases, however, where even compound colliders are not accurate enough. In 3D, you can use Mesh Colliders to match the shape of the object's mesh exactly. In 2D, the Polygon Collider 2D will generally not match the shape of the sprite graphic perfectly but you can refine the shape to any level of detail you like. These colliders are much more processor-intensive than primitive types, however, so use them sparingly to maintain good performance. Also, a mesh collider will normally be unable to collide with another mesh collider (ie, nothing will happen when they make contact). You can get around this in some cases by marking the mesh collider as Convex in the inspector. This will generate the collider shape as a "convex hull" which is like the original mesh but with any undercuts filled in. The benefit of this is that a convex mesh collider can collide with other mesh colliders so you may be able to use this feature when you have a moving character with a suitable shape. However, a good general rule is to use mesh colliders for scene geometry and approximate the shape of moving objects using compound primitive colliders.

Colliders can be added to an object without a Rigidbody component to create floors, walls and other motionless elements of a scene. These are referred to as static colliders. In general, you should not reposition static colliders by changing the Transform position since this will impact heavily on the performance of the physics engine. Colliders on an object that does have a Rigidbody are known as dynamic colliders. Static colliders can interact with dynamic colliders but since they don't have a Rigidbody, they will not move in response to collisions.

The reference pages for the various collider types linked above have further information about their properties and uses.

Physics Materials

When colliders interact, their surfaces need to simulate the properties of the material they are supposed to represent. For example, a sheet of ice will be slippery while a rubber ball will offer a lot of friction and be very bouncy. Although the shape of colliders is not deformed during collisions, their friction and bounce can be configured using Physics Materials. Getting the parameters just right can involve a bit of trial and error but an ice material, for example will have zero (or very low) friction and a rubber material with have high friction and near-perfect bounciness. See the reference pages for Physic Material and Physics Material 2D for further details on the available parameters. Note that for historical reasons, the 3D asset is actually called Physic Material (without the S) but the 2D equivalent is called Physics Material 2D (with the S).

Triggers

The scripting system can detect when collisions occur and initiate actions using the OnCollisionEnter function. However, you can also use the physics engine simply to detect when one collider enters the space of another without creating a collision. A collider configured as a Trigger (using the Is Trigger property) does not behave as a solid object and will simply allow other colliders to pass through. When a collider enters its space, a trigger will call the OnTriggerEnter function on the trigger object's scripts.

Script Actions Taken on Collision

When collisions occur, the physics engine calls functions with specific names on any scripts attached to the objects involved. You can place any code you like in these functions to respond to the collision event. For example, you might play a crash sound effect when a car bumps into an obstacle.

On the first physics update where the collision is detected, the OnCollisionEnter function is called. During updates where contact is maintained, OnCollisionStay is called and finally, OnCollisionExit indicates that contact has been broken. Trigger colliders call the analogous OnTriggerEnter, OnTriggerStay and OnTriggerExit functions. Note that for 2D physics, there are equivalent functions with 2D appended to the name, eg, OnCollisionEnter2D. Full details of these functions and code samples can be found on the Script Reference page for the MonoBehaviour class.

With normal, non-trigger collisions, there is an additional detail that at least one of the objects involved must have a non-kinematic Rigidbody (ie, Is Kinematic must be switched off). If both objects are kinematic Rigidbodies then OnCollisionEnter, etc, will not be called. With trigger collisions, this restriction doesn't apply and so both kinematic and non-kinematic Rigidbodies will prompt a call to OnTriggerEnter when they enter a trigger collider.

Joints

You can attach one rigidbody object to another or to a fixed point in space using a Joint component. Generally, you want a joint to allow at least some freedom of motion and so Unity provides different Joint components that enforce different restrictions. For example, a Hinge Joint allows rotation around a specific point and axis while a Spring Joint keeps the objects apart but lets the distance between them stretch slightly. As usual, the 2D components have 2D at the end of the name, eg, Hinge Joint 2D.

Joints also have other options that can enabled for specific effects. For example, you can set a joint to break when the force applied to it exceeds a certain threshold. Some joints also allow a drive force to occur between the connected objects to set them in motion automatically.

See the reference pages for the Joint classes to read further about their properties.

Character Controllers

The character in a first- or third-person game will often need some collision-based physics so that he doesn't fall through the floor or walk through walls. Usually, though, the character's acceleration and movement will not be physically realistic, so he may be able to accelerate, brake and change direction almost instantly without being affected by momentum.

In 3D physics, this type of behaviour can be created using a Character Controller. This component gives the character a simple, capsule-shaped collider that is always upright. The controller has its own special functions to set the object's speed and direction but unlike true colliders, a rigidbody is not needed and the momentum effects are not realistic.

A character controller cannot walk through static colliders in a scene, and so will follow floors and be obstructed by walls. It can push rigidbody objects aside while moving but will not be accelerated by incoming collisions. This means that you can use the standard 3D colliders to create a scene around which the controller will walk but you are not limited by realistic physical behaviour on the character itself.

You can find out more about character controllers on the reference page.

Page last updated: 2013-11-05



RandomNumbers

Randomly chosen items or values are important in many games. This sections shows how you can use Unity's built-in random functions to implement some common game mechanics.

Choosing a Random Item from an Array

Picking an array element at random boils down to choosing a random integer between zero and the array's maximum index value (which is equal to the length of the array minus one). This is easily done using the built-in Random.Range function:-

var element = myArray[Random.Range(0, myArray.Length)];

Note that Random.Range returns a value from a range that includes the first parameter but excludes the second, so using myArray.Length here gives the correct result.

Choosing Items with Different Probabilities

Sometimes, you need to choose items at random but with some items more likely to be chosen than others. For example, an NPC may react in several different ways when it encounters a player:-

You can visualise these different outcomes as a paper strip divided into sections each of which occupies a fraction of the strip's total length. The fraction occupied is equal to the probability of that outcome being chosen. Making the choice is equivalent to picking a random point along the strip's length (say by throwing a dart) and then seeing which section it is in.

In the script, the paper strip is actually an array of floats that contain the different probabilities for the items in order. The random point is obtained by multiplying Random.value by the total of all the floats in the array (they need not add up to 1; the significant thing is the relative size of the different values). To find which array element the point is "in", firstly check to see if it is less than the value in the first element. If so, then the first element is the one selected. Otherwise, subtract the first element's value from the point value and compare that to the second element and so on until the correct element is found. In code, this would look something like the following:-

function Choose(probs: float[]) {
	var total = 0;

	for (elem in probs) {
		total += elem;
	}

	var randomPoint = Random.value * total;

	for (i = 0; i < probs.Length; i++) {
		if (randomPoint < probs[i])
			return i;
		else
			randomPoint -= probs[i];
	}

	return probs.Length - 1;
}

Note that the final return statement is necessary because Random.value can return a result of 1. In this case, the search will not find the random point anywhere. Changing the line

if (randomPoint &lt; probs[i])

...to a less-than-or-equal test would avoid the extra return statement but would also allow an item to be chosen occasionally even when its probability is zero.

Shuffling a List

A common game mechanic is to choose from a known set of items but have them arrive in random order. For example, a deck of cards is typically shuffled so they are not drawn in a predictable sequence. You can shuffle the items in an array by visiting each element and swapping it with another element at a random index in the array:-

function Shuffle(deck: int[]) {
	for (i = 0; i < deck.Length; i++) {
		var temp = deck[i];
		var randomIndex = Random.Range(0, deck.Length);
		deck[i] = deck[randomIndex];
		deck[randomIndex] = temp;
	}
}

Choosing from a Set of Items Without Repetition

A common task is to pick a number of items randomly from a set without picking the same one more than once. For example, you may want to generate a number of NPCs at random spawn points but be sure that only one NPC gets generated at each point. This can be done by iterating through the items in sequence, making a random decision for each as to whether or not it gets added to the chosen set. As each item is visited, the probability of its being chosen is equal to the number of items still needed divided by the number still left to choose from.

As an example, suppose that ten spawn points are available but only five must be chosen. The probability of the first item being chosen will be 5 / 10 or 0.5. If it is chosen then the probability for the second item will be 4 / 9 or 0.44 (ie, four items still needed, nine left to choose from). However, if the first was not chosen then the probability for the second will be 5 / 9 or 0.56 (ie, five still needed, nine left to choose from). This continues until the set contains the five items required. You could accomplish this in code as follows:-

var spawnPoints: Transform[];

function ChooseSet(numRequired: int) {
	var result = new Transform[numRequired];

	var numToChoose = numRequired;

	for (numLeft = spawnPoints.Length; numLeft > 0; numLeft--) {
		// Adding 0.0 is simply to cast the integers to float for the division.
		var prob = numToChoose + 0.0 / numLeft + 0.0;

		if (Random.value <= prob) {
			numToChoose--;
			result[numToChoose] = spawnPoints[numLeft - 1];

			if (numToChoose == 0)
				break;
		}
	}

	return result;
}

Note that although the selection is random, items in the chosen set will be in the same order they had in the original array. If the items are to be used one at a time in sequence then the ordering can make them partly predictable, so it may be necessary to shuffle the array before use.

Random Points in Space

A random point in a cubic volume can be chosen by setting each component of a Vector3 to a value returned by Random.value:-

var randVec = Vector3(Random.value, Random.value, Random.value);

This gives a point inside a cube with sides one unit long. The cube can be scaled simply by multiplying the X, Y and Z components of the vector by the desired side lengths. If one of the axes is set to zero, the point will always lie within a single plane. For example, picking a random point on the "ground" is usually a matter of setting the X and Z components randomly and setting the Y component to zero.

When the volume is a sphere (ie, when you want a random point within a given radius from a point of origin), you can use Random.insideUnitSphere multiplied by the desired radius:-

var randWithinRadius = Random.insideUnitSphere * radius;

Note that if you set one of the resulting vector's components to zero, you will *not* get a correct random point within a circle. Although the point is indeed random and lies within the right radius, the probability is heavily biased toward the edge of the circle and so points will be spread very unevenly. You should use Random.insideUnitCircle for this task instead:-

var randWithinCircle = Random.insideUnitCircle * radius;

Page last updated: 2013-07-17



Particle Systems

Particle Systems in Unity are used to make clouds of smoke, steam, fire and other atmospheric effects.

Unity's particle system engine is called Shuriken. This section explains how you can use Shuriken effects to enhance your game.

Page last updated: 2013-08-01



Particle System Curve Editor

MinMax curves

Many of the properties in the particle system modules describe a change of a value with time. That change is described via MinMax Curves. These time-animated properties (for example size and speed), will have a pull down menu on the right hand side, where you can choose between:

Constant: The value of the property will not change with time, and will not be displayed in the Curve Editor

Curve: The value of the property will change with time based on the curve specified in the Curve Editor

A property animated with a Curve

Random between constants: The value of the property will be selected at random between the two constants

Random between curves: A curve will be generated at random between the min and the max curve, and the value of the property will change in time based on the generated curve

A property animated as Random Between Two Curves

In the Curve Editor, the x-axis spans time between 0 and the value specified by the Duration property, and the y-axis represents the value of the animated property at each point in time. The range of the y-axis can be adjusted in the number field in the upper right corner of the Curve Editor. The Curve Editor currently displays all of the curves for a particle system in the same window.

Multiple curves in the same curve editor

Note that the "-" in the bottom-right corner will remove the currently selected curve, while the "+" will optimize it (that is make it into a parametrized curve with at most 3 keys).

For animating properties that describe vectors in 3D space, we use the TripleMinMax Curves, which are simply curves for the x-,y-, and z- dimensions side by side, and it looks like this:

Managing many curves in the curve editor

To avoid cluttering in the Curve Editor, it is possible to toggle curves on and off, by clicking on them in the inspector. The Particle System Curve Editor can also be detached from the Inspector by right-clicking on the Particle System Curves title bar, after which you should see something like this:

A detached Curve Editor that can be docked like any other window

For more information on working with curves, take a look at the Curve Editor documentation

Page last updated: 2013-01-09



Particle System Color Editor

For properties that deal with color, the Particle System makes use of the Color and Gradient Editor. It works in a similar way to the Curve Editor.

The color-based properties will have a pull down menu on the right hand side, where you can choose between:

Gradient: The gradient (RGBA) will vary throughout time, edited in the Gradient Editor

Random Between Two Gradients: The gradient (RGBA) varies with time and is chosen at random between two values specified Gradient Editor

Page last updated: 2013-02-18



Particle System Gradient Editor

Gradient editor

The Gradient Editor is used for describing change of gradient with time. It animates the color (RGB-space, described by the markers at the bottom), and Alpha (described by the markers at the top).

You can add new markers for Alpha values by clicking near the top of the rectangle, and new ticks for Color by clicking near the bottom. The markers can be intuitively dragged along the timeline.

If an Alpha tick is selected, you can edit the value for that tick by dragging the alpha value.

If a Color tick is selected, the color can be modified by double clicking on the tick or clicking on the color bar.

To remove a marker, just drag it off the screen.

Page last updated: 2012-08-28



Particle System Inspector

The Particle System Inspector (Shuriken)

The Particle System Inspector shows one particle system at a time (the currently selected one), and it looks like this:

Individual particle systems can take on various complex behaviors by using Modules.

They can also be extended by being grouped together into Particle Effects.

If you press the button Open Editor ..., this will open up the Extended Particle Editor, that shows all of the particle systems under the same root in the scene tree. For more information on particle system grouping, see the section on Particle Effects.

Page last updated: 2012-08-28



Particle System Modules Intro

A Particle System consists of a predefined set of modules that can be enabled and disabled. These modules describe the behavior of particles in an individual particle system.

Initially only a few modules are enabled. Addding or removing modules changes the behavior of the particle system. You can add new modules by pressing the (+) sign in the top-right corner of the Particle System Inspector. This pops up a selection menu, where you can choose the module you want to enable.

An alternative way to work with modules is to select "Show All Modules", at which point all of the modules will show up in the inspector.

Then you can enable / disable modules directly from the inspector by clicking the checkbox to the left.

Most of the properties are controllable by curves (see Curve Editor). Color properties are controlled via gradients which define an animation for color (see Color Editor).

For details on individual modules and their properties, see Particle System Modules

Page last updated: 2012-10-25



Particle System Modules40

The Particle System (Shuriken) uses modules to describe the behaviour of particles over time. The modules are documented in detail here. For an introduction to modules see this page.

Initial Module

This module is always present, it cannot be removed or disabled.

DurationThe duration the Particle System will be emitting particles.
LoopingIs the Particle System looping.
PrewarmOnly looping systems can be prewarmed which means that the Particle System will have emitted particles at start as if it had already emitted particles one cycle.
Start DelayDelay in seconds that this Particle System will wait before emitting particles. Note prewarmed looping systems cannot use a start delay.
Start LifetimeThe lifetime of particles in seconds (see MinMaxCurve).
Start SpeedThe speed of particles when emitted (see MinMaxCurve).
Start SizeThe size of particles when emitted (see MinMaxCurve).
Start RotationThe rotation of particles when emitted (see MinMaxCurve).
Start ColorThe color of particles when emitted (see MinMaxGradient).
Gravity ModifierThe amount of gravity that will affect particles during their lifetime.
Inherit VelocityFactor for controlling the amount of velocity the particles should inherit of the transform of the Particle System (for moving Particle Systems).
Simulation SpaceSimulate the Particle System in local space or world space.
Play On AwakeIf enabled the Particle System will automatically start when it's created.
Max ParticlesMax number of particles the Particle System will emit.

Emission Module

Controls the rate of particles being emitted and allows spawning large groups of particles at certain moments (over Particle System duration time). Useful for explosions when a bunch of particles need to be created at once.

RateAmount of particles emitted over Time (per second) or Distance (per meter) (see MinMaxCurve).
Bursts (Time option only)Add bursts of particles that occur within the duration of the Particle System.
Time and Number of ParticlesSpecify time (in seconds within duration) that a specified amount of particles should be emitted. Use the + and - for adjusting number of bursts.

Shape Module

Defines the shape of the emitter: Sphere, Hemishpere, Cone, Box and Mesh. Can apply initial force along the surface normal or random direction.

Sphere 
RadiusRadius of the sphere. (Can also be manipulated by handles in the Scene View).
Emit from ShellEmit from shell of the sphere. If disabled, particles will be emitted from the volume of the sphere.
Random DirectionShould particles have a random direction when emitted or a direction along the surface normal of the sphere?
Hemisphere 
RadiusRadius of the hemisphere. (Can also be manipulated by handles in the Scene View).
Emit from ShellEmit from shell of the hemisphere. If disabled particles will be emitted from the volume of the hemisphere.
Random DirectionShould particles have a random direction when emitted or a direction along the surface normal of the hemisphere?
Cone 
AngleAngle of the cone. If angle is 0 then particles will be emitted in one direction. (Can also be manipulated by handles in the Scene View).
RadiusThe radius at the point of emission. If the value is near zero emission will be from a point. A larger value basically creates a capped cone, emission coming from a disc rather than a point. (Can also be manipulated by handles in the Scene View).
LengthLength of the emission volume. Only available when emitting from a Volume or Volume Shell. (Can also be manipulated by handles in the Scene View).
Emit FromDetermines where emission originates from. Possible values are Base, Base Shell, Volume and Volume Shell.
Random DirectionShould particles have a random direction when emitted or a direction along the cone?
Box 
Box XScale of box in X. (Can also be manipulated by handles in the Scene View).
Box YScale of box in Y. (Can also be manipulated by handles in the Scene View).
Box ZScale of box in Z. (Can also be manipulated by handles in the Scene View).
Random DirectionShould particles have a random direction when emitted or a direction along the Z-axis of the box?
Mesh 
TypeParticles can be emitted from either Vertex, Edge or Triangle.
MeshSelect Mesh that should be used as emission shape.
Random DirectionShould particles have a random direction when emitted or a direction along the surface of the mesh?

Velocity Over Lifetime Module

Directly animates velocity of the particle. Mostly useful for particles which has complex physical, but simple visual behavior (like smoke with turbulence and temperature loss) and has little interaction with physical world.

XYZUse either constant values for curves or random between curves for controlling the movement of the particles. See MinMaxCurve.
SpaceLocal / World: Are the velocity values in local space or world space?

Limit Velocity Over Lifetime Module

Basically can be used to simulate drag. Dampens or clamps velocity, if it is over certain threshold. Can be configured per axis or per vector length.

Separate AxisUse for setting per axis control.
SpeedSpecify magnitude as constant or by curve that will limit all axes of velocity. See MinMaxCurve.
Dampen(0-1) value that controls how much the exceeding velocity should be dampened. For example, a value of 0.5 will dampen exceeding velocity by 50%.

Force Over Lifetime Module

XYZUse either constant values for curves or random between curves for controlling the force applied to the particles. See MinMaxCurve.
SpaceLocal / World: Are the velocity values in local space or world space
RandomizeRandomize the force applied to the particles every frame.

Color Over Lifetime Module

ColorControls the color of each particle during its lifetime. If some particles have a shorter lifetime than others, they will animate faster. Use constant color, random between two colors, animate it using gradient or specify a random color using two gradients (see Gradient). Note that this colour will be multiplied by the value in the Start Color property - if the Start Color is black then Color Over Lifetime will not affect the particle.

Color By Speed Module

Animates particle color based on its speed. Remaps speed in the defined range to a color.

ColorColor used for remapping of speed. Use gradients for varying colors. See MinMaxGradient.
Speed RangeThe min and max values for defining the speed range which is used for remapping a speed to a color.

Size Over Lifetime Module

SizeControls the size of each particle during its lifetime. Use constant size, animate it using a curve or specify a random size using two curves. See MinMaxCurve.

Size By Speed Module

SizeSize used for remapping of speed. Use curves for varying sizes. See MinMaxCurve.
Speed RangeThe min and max values for defining the speed range which is used for remapping a speed to a size.

Rotation Over Lifetime Module

Specify values in degrees.

Angular VelocityControls the rotational speed of each particle during its lifetime. Use constant rotational speed, animate it using a curve or specify a random rotational speed using two curves. See MinMaxCurve.

Rotation By Speed Module

Angular VelocityRotational speed used for remapping of a particle's speed. Use curves for varying rotational speeds. See MinMaxCurve.
Speed RangeThe min and max values for defining the speed range which is used for remapping a speed to a rotational speed.

External Forces Module

MultiplierScale factor that determines how much the particles are affected by wind zones (i.e., the wind force vector is multiplied by this value).

Collision Module

Set up collisions for the particles of this Particle System. World and planar collisions are supported. Planar collision is very efficient for simple collision detection. Planes are set up by referencing an existing transform in the scene or by creating a new empty GameObject for this purpose. Another benefit of planar collision is that particle systems with collision planes can be set up as prefabs. World collision uses raycasts so must be used with care in order to ensure good performance. However, for cases where approximate collisions are acceptable world collision in Low or Medium quality can be very efficient.

Properties common for any Collision Module

Planes/WorldSpecify the collision type: Planes for planar collision or World for world collisions.
Dampen(0-1) When the particle collides, it will keep this fraction of its speed. Unless it is set to 1.0, the particle will become slower after collision.
Bounce(0-1) When the particle collides, it will keep this fraction of the component of the velocity, which is normal to the plane of collision.
Lifetime Loss(0-1) The fraction of Start Lifetime lost on each collision. When lifetime reaches 0, the particle dies. For example if a particle should die on first collision, set this to 1.0.
Min Kill SpeedThe minimum speed of a particle before it is killed.
Send Collision MessagesWhether to send collision messages and thus trigger OnParticleCollision callbacks on GameObjects and ParticleSystems.

Properties available only in the Planes Mode

PlanesPlanes are defined by assigning a reference to a transform. This transform can be any transform in the scene and can be animated. Multiple planes can be used. Note: the Y-axis is used as the normal of a plane.
VisualizationOnly used for visualizing the planes: Grid or Solid.
GridRendered as gizmos and is useful for quick indication of position and orientation in the world.
SolidRenders a plane in the scene which is useful for exact positioning of a plane.
Scale PlaneResizes the visualization planes.
Particle RadiusThe assumed radius of the particle for collision purposes. (So particles are treated as spheres.)

Properties available only in the World Mode

Collides WithFilter for specifying colliders. Select Everything to colllide with the whole world.
Collision QualityThe quality of the world collision.
HighAll particles performs a scene raycast per frame. Note: This is CPU intensive, it should only be used with 1000 simultaneous particles (scene wide) or less.
MediumThe particle system receives a share of the globally set Particle Raycast Budget (see Particle Raycast Budget) in each frame. Particles are updated in a round-robin fashion where particles that do not receive a raycast in a given frame will lookup and use older collisions stored in a cache. Note: This collision type is approximate and some particles will leak, particularly at corners.
LowSame as Medium except the particle system is only awarded a share of the Particle Raycast Budget every fourth frame.
Voxel SizeDensity of the voxels used for caching intersections used in the Medium and Low quality setting. The size of a voxel is given in scene units. Usually, 0.5 - 1.0 should be used (assuming metric units).

Sub Emitter Module

This is a powerful module that enables spawning of other Particle Systems at the follwing particle events: birth, death or collision of a particle.

BirthSpawn another Particle System at birth of each particle in this Particle System.
DeathSpawn another Particle System at death of each particle in this Particle System.
CollisionSpawn another Particle System at collision of each particle in this Particle System. IMPORTANT: Collision needs to be set up using the Collision Module. See Collision Module.

Texture Sheet Animation Module

Animates UV coordinates of the particle over its lifetime. Animation frames can be presented in a form of a grid or every row in the sheet can be separate animation. The frames are animated with curves or can be a random frame between two curves. The speed of the animation is defined by "Cycles".

IMPORTANT: The texture used for animation is the one used by the material found in the Renderer module.
TilesDefine the tiling of the texture.
AnimationSpecify the animation type: Whole Sheet or Single Row.
Whole SheetUses the whole sheet for uv animation.
- Frame over TimeControls the uv animation frame of each particle during its lifetime over the whole sheet. Use constant, animate it using a curve or specify a random frame using two curves. See MinMaxCurve.
Single RowUses a single row of the texture sheet for uv animation.
- Random RowIf checked, the start row will be random, and if unchecked, the row index can be specified (first row is 0).
- Frame over TimeControls the uv animation frame of each particle during its lifetime within the specified row. Use constant, animate it using a curve or specify a random frame using two curves. See MinMaxCurve.
- CyclesSpecify speed of animation.

Renderer Module

The renderer module exposes the ParticleSystemRenderer component's properties. Note that even though a GameObject has a ParticleSystemRenderer component, its properties are only exposed here. When this module is removed/added, it is actually the ParticleSystemRenderer component that is added or removed.

Render ModeSelect one of the following particle render modes.
BillboardMakes the particles always face the camera.
Stretched BillboardParticles are stretched using the following parameters.
- Camera ScaleHow much the camera speed is factored in when determining particle stretching.
- Speed ScaleDefines the length of the particle compared to its speed.
- Length ScaleDefines the length of the particle compared to its width.
Horizontal BillboardMakes the particles align with the XZ plane.
Vertical BillboardMakes the particles align with the Y axis while facing the camera.
MeshParticles are rendered using a mesh instead of a quad.
- MeshThe reference to the mesh used for rendering particles.
Normal DirectionValue from 0 to 1 that determines how much normals point toward the camera (0) and how much sideways toward the centre of the view (1).
MaterialMaterial used by billboarded or mesh particles.
Sort ModeThe draw order of particles can be sorted by distance, youngest first, or oldest first.
Sorting FudgeUse this to affect the draw order. Particle systems with lower sorting fudge numbers are more likely to be drawn last, and thus appear in front of other transparent objects, including other particles.
Cast ShadowsShould particles cast shadows? May or may not be possible depending on the material.
Receive ShadowsShould particles receive shadows? May or may not be possible depending on the material.
Max Particle SizeSet max relative viewport size. Valid values: 0-1.

Page last updated: 2013-03-12



Particle System Grouping

An important feature of Unity's Particle System is that individual Particle Systems can be grouped by being parented to the same root. We will use the term Paricle Effect for such a group. Particle Systems belonging to the same Particle Effect, are played, stopped and paused together.

For managing complex particle effects, Unity provides a Particle Editor, which can be accessed from the Inspector, by pressing Open Editor

Overview of the Particle System Editor

You can toggle between Show: All and Show: Selected in this Editor. Show: All will render the entire particle effect. Show: Selected will only render the selected particle systems. What is selected will be highlighted with a blue frame in the Particle Editor and also shown in blue in the Hierarchy view. You can also change the selection both from the Hierarchy View and the Particle Editor, by clicking the icon in the top-left corner of the Particle System. To do a multiselect, use Ctrl+click on windows and Command+click on the Mac.

You can explicitly control rendering order of grouped particles (or otherwise spatially close particle emitters) by tweaking Sorting Fudge property in the Renderer module.

Particle Systems in the same hierarchy are considered as part of the same Particle Effect. This hierarchy shows the setup of the effect shown above.

Page last updated: 2013-07-17



Mecanim Animation System

Unity has a rich and sophisticated animation system called Mecanim. Mecanim provides:

Typical setup in the Visual Programming Tool and the Animation Preview window

Mecanim workflow

Workflow in Mecanim can be split into three major stages.

  1. Asset preparation and import. This is done by artists or animators, with 3rd party tools, such as Max or Maya. This step is independent of Mecanim features.
  2. Character setup for Mecanim, which can be done in 2 ways:
    • Humanoid character setup. Mecanim has a special workflow for humanoid models, with extended GUI support and retargeting. The setup involves creating and setting up an Avatar and tweaking Muscle definitions.
    • Generic character setup. This is for anything like creatures, animated props, four-legged animals, etc. Retargeting is not possible here, but you can still take advantage of the rich feature set of Mecanim, including everything described below.
  3. Bringing characters to life. This involves setting up animation clips, as well as interactions between them, and involves setup of State Machines and Blend Trees, exposing Animation Parameters, and controlling animations from code.

Mecanim comes with a lot of new concepts and terminology. If at any point, you need to find out what something means, go to our Animation Glossary.

Legacy animation system

While Mecanim is recommended for use in most situations, especially for working humanoid animations, the Legacy animation system is still used in a variety of contexts. One of them is working legacy animations and code (content created before Unity 4.0). Another is controlling animation clips with parameters other than time (for example for controlling the aiming angle). For information on the Legacy animation system, see this section

Unity intends to phase out the Legacy animation system over time for all cases by merging the workflows into Mecanim.

Page last updated: 2013-02-14



A glossary of animation and Mecanim terms

Animation Clip terms

Animation Clip
Animation data that can be used for animated characters or simple animations. It is a simple "unit" piece of motion, such as (one specific instance of) "Idle", "Walk" or "Run".
Body Mask
A specification for which body parts to include or exclude for a skeleton. Used in Animation Layers and in the importer.
Animation Curves
Curves can be attached to animation clips and controlled by various parameters from the game.

Avatar terms

Avatar
An interface for retargeting one skeleton to another.
Retargeting
Applying animations created for one model to another.
Rigging
The prcoess of building a skeleton hierarchy of bone joints for your mesh. Performed with an external tool, such as Max or Maya.
Skinning
The process of binding bone joints to the character's mesh or 'skin'. Performed with an external tool, such as Max or Maya.
Muscle Definition
A Mecanim concept, which allows you to have a more intuitive control over the character's skeleton. When an Avatar is in place, Mecanim works in muscle space, which is more intuitive than bone space.
T-pose
The pose in which the character has his arms straight out to the sides, forming a "T". The required pose for the character to be in, in order to make an Avatar.
Bind-pose
The pose at which the character was modelled.
Human template
A pre-defined bone-mapping. Used for matching bones from FBX files to the Avatar.

Animator and Animator Controller terms

Animator Component
Component on a model that animates that model using the Mecanim animation system. The component has a reference to an Animator Controller asset that controls the animation.
Root Motion
Motion of character's root, whether it's controlled by the animation itself or externally.
Animator Controller (Asset)
The Animator Controller controls animation through Animation Layers with Animation State Machines and Animation Blend Trees, controlled by Animation Parameters. The same Animator Controller can be referenced by multiple models with Animator components.
Animator Controller (Window)
The window where the Animator Controller Asset is visualized and edited.
Animation Layer
An Animation Layer contains an Animation State Machine that controls animations of a model or part of it. An example of this is if you have a full-body layer for walking or jumping and a higher layer for upper-body motions such as throwing an object or shooting. The higher layers take precedence for the body parts they control.
Animation State Machine
A graph controlling the interaction of Animation States. Each state references an Animation Blend Tree or a single Animation Clip.
Animation Blend Tree
Used for continuous blending between similar Animation Clips based on float Animation Parameters.
Animation Parameters
Used to communicate between scripting and the Animator Controller. Some parameters can be set in scripting and used by the controller, while other parameters are based on Custom Curves in Animation Clips and can be sampled using the scripting API.
Inverse Kinematics (IK)
The ability to control the character's body parts based on various objects in the world.

Page last updated: 2013-07-17



Asset Preparation and Import

This section explains how to obtain and prepare character assets for use with Mecanim.

Page last updated: 2013-07-17



UsingHumanoidChars

In order to take full advantage of Mecanim's humanoid animation system and retargeting, you need to have a rigged and skinned humanoid type mesh.

  1. A character model is generally made up of polygons in a 3D package or converted to polygon or triangulated mesh, from a more complex mesh type before export.
  2. A joint hierarchy or skeleton which defines the bones inside the mesh and their movement in relation to one another, must be created to control the movement of the character. The process for creating the joint hierarchy is known as rigging.
  3. The mesh or skin must then be connected to the joint hierarchy in order to define which parts of the character mesh move when a given joint is animated. The process of connecting the skeleton to the mesh is known as skinning.
Stages for preparing a character (modeling, rigging, and skinning)

How to obtain humanoid models

There are three main ways to obtain humanoid models for with the Mecanim Animation system:

  1. Use a procedural character system or character generator such as Poser, Makehuman or Mixamo. Some of these systems will rig and skin your mesh (eg, Mixamo) while others will not. Furthermore, these methods may require that you reduce the number of polygons in your original mesh to make it suitable for use in Unity.
  2. Purchase demo examples and character content from the Unity Asset Store.
  3. Also, you can of course prepare your own character from scratch.

Export & Verify

Unity imports a number of different generic and native 3D file formats. The format we recommend for exporting and verifying your model is FBX 2012 since it will allow you to:

Page last updated: 2013-07-17



Preparing your own character

There are three main steps in creating an animated humanoid character from scratch: modelling, rigging and skinning.

Modelling

This is the process of creating your own humanoid mesh in a 3D modelling package - 3DSMax, Maya, Blender, etc. Although this is a whole subject in its own right, there are a few guidelines you can follow to ensure a model works well with animation in a Unity project.

Skin Mesh, textured and triangulated

Rigging

This is the process of creating a skeleton of joints to control the movements of your model.

3D packages provide a number of ways to create joints for your humanoid rig. These range from ready-made biped skeletons that you can scale to fit your mesh, right through to tools for individual bone creation and parenting to create your own bone structure. To work with Mecanim, the hips should be the root element of the bone hierarchy. A minimum of fifteen bones are required in the skeleton.

The joint/bone hierachy should follow a natural structure for the character you are creating. Given that arms and legs come in pairs, you should use a consistent convention for naming them (eg, "arm_L" for the left arm, "arm_R" for the right arm, etc). Possible structures for the hierarchy might be:-

  • HIPS - spine - chest - shoulders - arm - forearm - hand
  • HIPS - spine - chest - neck - head
  • HIPS - UpLeg - Leg - foot - toe - toe_end

Biped Skeleton, positioned in T-pose

Skinning

This is the process of attaching the mesh to the skeleton

Skinning involves binding vertices in your mesh to bones, either directly (rigid bind) or with blended influence to a number of bones (soft bind). Different software packages use different methods, eg, assigning individual vertices and painting the weighting of influence per bone onto the mesh. The initial setup is typically automated, say by finding the nearest influence or using "heatmaps". Skinning usually requires a fair amount of work and testing with animations in order to ensure satisfactory results for the skin deformation. Some general guidelines for this process include:

Interactive Skin Bind, one of many skinning methods

Page last updated: 2013-07-17



Importing Animations

Before a character model can be used, it must first be imported into your project. Unity can import native Maya (.mb or .ma) and Cinema 4D (.c4d) files, and also generic FBX files which can be exported from most animation packages (see this page for further details on exporting). To import an animation, simply drag the model file to the Assets folder of your project. When you select the file in the Project View you can edit the Import Settings in the inspector:-


The Import Settings Dialog for a mesh

See the FBX importer page for a full description of the available import options.

Splitting animations

(back to Mecanim introduction)

Page last updated: 2012-11-01



Splitting animations

An animated character typically has a number of different movements that are activated in the game in different circumstances. These movements are called Animation Clips. For example, we might have separate animation clips for walking, running, jumping, throwing, dying, etc. Depending on the way the model was animated, these separate movements might be imported as distinct animation clips or as one single clip where each movement simply follows on from the previous one. In cases where there is only a single clip, the clip must be split into its component animation clips within Unity, which will involve some extra steps in your workflow.

Working with models that have pre-split animations

The simplest types of models to work with are those that contain pre-split animations. If you have an animation like that, the Animations tab in the Animation Importer Inspector will look like this:

You will see a list available clips which you can preview by pressing Play in the Preview Window (lower down in the inspector). The frame ranges of the clips can be edited, if needed.

Working with models that have unsplit animations

For models where the clips are supplied as one continuous animation, the Animation tab in the Animation Importer Inspector will look like this:

In cases like this, you can define the frame ranges that correspond to each of the separate animation sequences (walking, jumping, etc). You can create a new animation clip by pressing (+) and selecting the range of frames that are included in it.

For example:


The Import Settings Options for Animation

In the Import Settings, the Split Animations table is where you tell Unity which frames in your asset file make up which Animation Clip. The names you specify here are used to activate them in your game.

For further information about the animation inspector, see the Animation Clip component reference page.

Adding animations to models that do not contain them

You can add animation clips to an Animation component even for models without muscle definitions (ie, non-Mecanim). You need to specify the default animation clip in the Animation property, and the available animation clips in the Animations property. The animation clips you add to such a non-Mecanim model should also be setup in a non-Mecanim way (ie, the Muscle Definition property should be set to None)

For models that have muscle definitions (Mecanim), the process is different:-

Importing Animations using multiple model files

Another way to import animations is to follow a naming scheme that Unity allows for the animation files. You create separate model files and name them with the convention 'modelName@animationName.fbx'. For example, for a model called "goober", you could import separate idle, walk, jump and walljump animations using files named "goober@idle.fbx", "goober@walk.fbx", "goober@jump.fbx" and "goober@walljump.fbx". Only the animation data from these files will be used, even if the original files are exported with mesh data.

An example of four animation files for an animated character (note that the .fbx suffix is not shown within Unity)

Unity automatically imports all four files and collects all animations to the file without the @ sign in. In the example above, the goober.mb file will be set up to reference idle, jump, walk and wallJump automatically.

For FBX files, simply export a model file with no animation ticked (eg, goober.fbx) and the 4 clips as goober@animname.fbx by exporting the desired keyframes for each (enable animation in the FBX dialog).

(back to Mecanim introduction)

Page last updated: 2013-01-15



Avatar Creation and Setup

The Mecanim Animation System is particularly well suited for working with animations for humanoid skeletons. Since humanoid skeletons are a very common special case and are used extensively in games, Unity provides a specialized workflow, and an extended tool set for humanoid animations.

Because of the similarity in bone structure, it is possible to map animations from one humanoid skeleton to another, allowing retargeting and inverse kinematics.
With rare exceptions, humanoid models can be expected to have the same basic structure, representing the major articulate parts of the body, head and limbs. The Mecanim system makes good use of this idea to simplify the rigging and control of animations. A fundamental step in creating a animation is to set up a mapping between the simplified humanoid bone structure understood by Mecanim and the actual bones present in the skeleton; in Mecanim terminology, this mapping is called an Avatar. The pages in this section explain how to create an Avatar for your model.

Page last updated: 2012-11-08



Creating the Avatar

After a model file (FBX, COLLADA, etc.) is imported, you can specify what kind of rig it is in the Rig tab of the ModelImporter options.

Humanoid animations

For a Humanoid rig, select Humanoid and click Apply. Mecanim will attempt to match up your existing bone structure to the Avatar bone structure. In many cases, it can do this automatically by analysing the connections between bones in the rig.

If the match has succeeded, you will see a check mark next to the Configure menu

Also, in the case of a successful match, an Avatar sub-asset is added to the model asset, which you will be able to see in the project view hierarchy.


Models with and without an Avatar sub-asset

The inspector for an Avatar asset

If Mecanim was unable to create the Avatar, you will see a cross next to the Configure button, and no Avatar sub-asset will be added. When this happens, you need to configure the avatar manually.

Non-humanoid animations

Two options for non-humanoid animation are provided: Generic and Legacy. Generic animations are imported using the Mecanim system but don't take advantage of the extra features available for humanoid animations. Legacy animations use the the animation system that was provided by Unity before Mecanim. There are some cases where it is still useful to work with legacy animations (most notably with legacy projects that you don't want to update fully) but they are seldom needed for new projects. See this section of the manual for further details on legacy animations.

Page last updated: 2013-11-27



Configuring the Avatar

Since the Avatar is such an important aspect of the Mecanim system, it is important that it is configured properly for your model. So, whether the automatic Avatar creation fails or succeeds, you need to go into the Configure Avatar mode to ensure your Avatar is valid and properly set up. It is important that your character's bone structure matches Mecanim's predefined bone structure and that the model is in T-pose.

If the automatic Avatar creation fails, you will see a cross next to the Configure button.

If it succeeds, you will see a check/tick mark:

Here, success simply means all of the required bones have been matched but for better results, you might want to match the optional bones as well and get the model into a proper T-pose.

When you go to the Configure ... menu, the editor will ask you to save your scene. The reason for this is that in Configure mode, the Scene View is used to display bone, muscle and animation information for the selected model alone, without displaying the rest of the scene.

Once you have saved the scene, you will see a new Avatar Configuration inspector, with a bone mapping.

The inspector shows which of the bones are required and which are optional - the optional ones can have their movements interpolated automatically. For Mecanim to produce a valid match, your skeleton needs to have at least the required bones in place. In order to improve your chances for finding a match to the Avatar, name your bones in a way that reflects the body parts they represent (names like "LeftArm", "RightForearm" are suitable here).

If the model does NOT yield a valid match, you can manually follow a similar process to the one used internally by Mecanim:-

  1. Sample Bind-pose (try to get the model closer to the pose with which it was modelled, a sensible initial pose)
  2. Automap (create a bone-mapping from an initial pose)
  3. Enforce T-pose (force the model closer to T-pose, which is the default pose used by Mecanim animations)

If the auto-mapping (Mapping->Automap) fails completely or partially, you can assign bones by either draging them from the Scene or from the Hierarchy. If Mecanim thinks a bone fits, it will show up as green in the Avatar Inspector, otherwise it shows up in red.

Finally, if the bone assignment is correct, but the character is not in the correct pose, you will see the message "Character not in T-Pose". You can try to fix that with Enforce T-Pose or rotate the remaining bones into T-pose.

Human Template files

You can save the mapping of bones in your skeleton to the Avatar on disk as a "human template file" (extention *.ht), which can be reused by any characters that use this mapping. This is useful, for example, if your animators use a consistent layout and naming convention for all skeleton but Mecanim doesn't know how to interpret it. You can then Load the .ht file for each model, so that manual remapping only needs to be done once.

(back to Avatar Creation and Setup)

(back to Mecanim introduction)

Page last updated: 2012-11-05



Muscle Definitions

Mecanim allows you to control the range of motion of different bones using Muscles.

Once the Avatar has been properly configured, Mecanim will "understand" the bone structure and allow you to start working in the Muscles tab of the Avatar Inspector. Here, it is very easy to tweak the character's range of motion and ensure the character deforms in a convincing way, free from visual artifacts or self-overlaps.

You can either adjust individual bones in the body (lower part of the view) or manipulate the character using predefined deformations which operate on several bones at once (upper part of the view).

Muscle Clips

In the Animation tab, you can set up Muscle Clips, which are animations for specific muscles and muscle groups.

You can also define which body parts these muscle clips apply to.

(back to Avatar Creation and Setup)

(back to Mecanim introduction)

Page last updated: 2012-11-01



Avatar Body Mask

Specific body parts can be selectively enabled or disabled in an animation using a so-called Body Mask. Body masks are used in the Animation tab of the mesh import inspector and Animation Layers. Body masks enable you to tailor an animation to fit the specific requirements of your character more closely. For example, you may have a standard walking animation that includes both arm and leg motion, but if a character is carrying a large object with both hands then you wouldn't want his arms to swing by his sides as he walks. However, you could still use the standard walking animation by switching off the arm movements in the body mask.

The body parts included are: Head, Left Arm, Right Arm, Left Hand, Right Hand, Left Leg, Right Leg and Root (which is denoted by the "shadow" under the feet). In the body mask, you can also toggle inverse kinematics (IK) for hands and feet, which will determine whether or not IK curves will be included in animation blending.

Body mask in the Body Mask inspector (arms excluded)

In the Animation tab of the mesh import inspector, you will see a list entitled Clips that contains all the object's animation clips. When you select an item from this list, options for the clip will be shown, including the body mask editor.

You can also create Body Mask Assets (Assets->Create->Avatar Body Mask), which show up as .mask files on disk.

The BodyMask assets can be reused in Animator Controllers, when specifying Animation Layers

A benefit of using body masks is that they tend to reduce memory overheads since body parts that are not active do not need their associated animation curves. Also, the unused curves need not be calculated during playback which will tend to reduce the CPU overhead of the animation.

Page last updated: 2012-10-18



Retargeting

One of the most powerful features of Mecanim is retargeting of humanoid animations. This means that with relative ease, you can apply the same set of animations to various character models. Retargeting is only possible for humanoid models, where an Avatar has been configured, because this gives us a correspondence between the models' bone structure.

Recommended Hierarchy structure

When working with Mecanim animations, you can expect your scene to contain the following elements:-

Your project should also contain another character model with a valid Avatar.

If in doubt about the terminology, consult the Animation Glossary

The recommended setup is to:

Then in order to reuse the same animations on another model, you need to:

(back to Mecanim introduction)

Page last updated: 2013-08-16



Inverse Kinematics

Most animation is produced by rotating the angles of joints in a skeleton to predetermined values. The position of a child joint changes according to the rotation of its parent and so the end point of a chain of joints can be determined from the angles and relative positions of the individual joints it contains. This method of posing a skeleton is known as forward kinematics.

However, it is often useful to look at the task of posing joints from the opposite point of view - given a chosen position in space, work backwards and find a valid way of orienting the joints so that the end point lands at that position. This can be useful when you want a character to touch an object at a point selected by the user or plant its feet convincingly on an uneven surface. This approach is known as Inverse Kinematics (IK) and is supported in Mecanim for any humanoid character with a correctly configured Avatar.

To set up IK for a character, you typically have objects around the scene that a character interacts with, and then set up the IK thru script, in particular, Animator functions like SetIKPositionWeight, SetIKRotationWeight, SetIKPosition, SetIKRotation, SetLookAtPosition, bodyPosition, bodyRotation

In the illustration above, we show a character grabbing a cylindrical object. How do we make this happen?

We start out with a character that has a valid Avatar, and attach to it a script that actually takes care of the IK, let's call it IKCtrl:

using UnityEngine;
using System;
using System.Collections;

[RequireComponent(typeof(Animator))]  

public class IKCtrl : MonoBehaviour {

	protected Animator animator;

	public bool ikActive = false;
	public Transform rightHandObj = null;

	void Start () 
	{
		animator = GetComponent<Animator>();
	}

        //a callback for calculating IK
	void OnAnimatorIK()
	{
	      if(animator) {

                        //if the IK is active, set the position and rotation directly to the goal. 
			if(ikActive) {

                                //weight = 1.0 for the right hand means position and rotation will be at the IK goal (the place the character wants to grab)
				animator.SetIKPositionWeight(AvatarIKGoal.RightHand,1.0f);
				animator.SetIKRotationWeight(AvatarIKGoal.RightHand,1.0f);

			        //set the position and the rotation of the right hand where the external object is
				if(rightHandObj != null) {
					animator.SetIKPosition(AvatarIKGoal.RightHand,rightHandObj.position);
					animator.SetIKRotation(AvatarIKGoal.RightHand,rightHandObj.rotation);
				}					

			}

                        //if the IK is not active, set the position and rotation of the hand back to the original position
			else {			
				animator.SetIKPositionWeight(AvatarIKGoal.RightHand,0);
				animator.SetIKRotationWeight(AvatarIKGoal.RightHand,0);				
			}
		}
	}	  
}

As we do not intend for the character to grab the entire object with his hand, we position a sphere where the hand should be on the cylinder, and rotate it accordingly.

This sphere should then be placed as the "Right Hand Obj" property of the IKCtrl script

Observe the character grabbing and ungrabbing the object as you click the IKActive checkbox

(back to Mecanim introduction)

Page last updated: 2013-04-23



Generic Animations

The full power of Mecanim is most evident when you are working with humanoid animations. However, non-humanoid animations are also supported although without the avatar system and other features. In Mecanim terminology, non-humanoid animations are referred to as Generic Animations.

To start working with a generic skeleton, go to the Rig tab in the FBX importer and choose Generic from the Animation Type menu.

Root node in generic animations

While in the case of humanoid animations, we have the knowledge about the center of mass and orientation, in the case of Generic animations, the skeleton can be arbitrary, and we need to specify a reference bone, or the "root node". Selecting the root node allows us to establish correspondence between animation clips for a generic model, and blend properly between animations that are not "in place". The root node is also essential for separating animation of bones relative to reach other and motion of the root in the world (controlled from OnAnimatorMove).

Page last updated: 2013-10-10



Bringing characters to life

Once the character mesh and animations are imported and the avatar is set up, you are ready to start making use of them in your game. The following sections cover the main features that Mecanim provides for controlling and sequencing your animations.

Page last updated: 2012-11-08



Looping Animation Clips

A common operation for people working with animations is to make sure they loop properly. It is important, for example, that the animation clip representing the walk cycle, begins and ends in a similar pose (e.g. left foot on the ground), to ensure there is no foot sliding, or strange jerky motions. Mecanim provides convenient tools for this. Animation clips can loop based on pose, rotation, and position.

If you drag the Start or End points of the animation clip, you will see the Looping fitness curves for all of the paramers based on which it is possible to loop. If you place the Start / End marker in a place where the curve for the property is green, it is more likely that the clip can loop properly. The loop match indicator will show how good the looping is for the selected ranges.

Clip ranges with bad match for Loop Pose

Clip ranges with good match for Loop Pose

Once the loop match indicator is green, Enabling Loop Pose (for example) will make sure the looping of the pose is artifact-free.

For more details on animation clip options, see Animation Clip reference
(back to Mecanim introduction)

Page last updated: 2012-11-12



Animator Component and Window

The avatar defines an object's skeletal structure but an Animator Controller is also required to apply animations to the skeleton. An Animator Controller asset is created within Unity and allows you to maintain a set of animations for a character and switch between them when certain game conditions occur. For example, you could switch from a walk animation to a jump whenever the spacebar is pressed. The controller manages the transitions between animations using a so-called State Machine, a kind of simple program written in a visual programming language within Unity. More information about state machines can be found here.


A simple Animator Controller

The avatar and animator controller are finally applied to an object by attaching an Animator component that references them. See the reference manual pages about the Animator component and AnimatorController for further details about their use.

Page last updated: 2013-10-15



Animation State Machines

It is common for a character to have several different animations that correspond to different actions it can perform in the game. For example, it may breathe or sway slightly while idle, walk when commanded to and raise its arms in panic as it falls from a platform. Controlling when these animations are played back is potentially quite a complicated scripting task. Mecanim borrows a computer science concept known as a state machine to simplify the control and sequencing of a character's animations. This section gives further details about Mecanim's state machines and explains how to use them.

Page last updated: 2013-07-17



StateMachineBasics

The basic idea is that a character is engaged in some particular kind of action at any given time. The actions available will depend on the type of gameplay but typical actions include things like idling, walking, running, jumping, etc. These actions are referred to as states, in the sense that the character is in a "state" where it is walking, idling or whatever. In general, the character will have restrictions on the next state it can go to rather than being able to switch immediately from any state to any other. For example, a running jump can only be taken when the character is already running and not when it is at a standstill, so it should never switch straight from the idle state to the running jump state. The options for the next state that a character can enter from its current state are referred to as state transitions. Taken together, the set of states, the set of transitions and the variable to remember the current state form a state machine.

The states and transitions of a state machine can be represented using a graph diagram, where the nodes represent the states and the arcs (arrows between nodes) represent the transitions. You can think of the current state as being a marker or highlight that is placed on one of the nodes and can then only jump to another node along one of the arrows.

The importance of state machines for animation is that they can be designed and updated quite easily with relatively little coding. Each state has a Motion associated with it that will play whenever the machine is in that state. This enables an animator or designer to define the possible sequences of character actions and animations without being concerned about how the code will work.

Mecanim State Machines

Mecanim's Animation State Machines provide a way to overview all of the animation clips related to a particular character and allow various events in the game (for example user input) to trigger different animations.

Animation State Machines can be set up from the Animator Controller Window, and they look something like this:

State Machines consist of States, Transitions and Events and smaller Sub-State Machines can be used as components in larger machines.

Page last updated: 2013-07-17



Animation States

Animation States are the basic building blocks of an Animation State Machine. Each state contains an individual animation sequence (or blend tree) which will play while the character is in that state. When an event in the game triggers a state transition, the character will be left in a new state whose animation sequence will then take over.

When you select a state in the Animator Controller, you will see the properties for that state in the inspector:-

SpeedThe default speed of the animation
MotionThe animation clip assigned to this state
Foot IKShould Foot IK be respected for this state
TransitionsThe list of transitions originating from this state

The default state, displayed in brown, is the state that the machine will be in when it is first activated. You can change the default state, if necessary, by right-clicking on another state and selecting Set As Default from the context menu. The solo and mute checkboxes on each transition are used to control the behaviour of animation previews - see this page for further details.

A new state can be added by right-clicking on an empty space in the Animator Controller Window and selecting Create State->Empty from the context menu. Alternatively, you can drag an animation into the Animator Controller Window to create a state containing that animation. (Note that you can only drag Mecanim animations into the Controller - non-Mecanim animations will be rejected.) States can also contain Blend Trees.

Any State

Any State is a special state which is always present. It exists for the situation where you want to go to a specific state regardless of which state you are currently in. This is a shorthand way of adding the same outward transition to all states in your machine. Note that the special meaning of Any State implies that it cannot be the end point of a transition (ie, jumping to "any state" cannot be used as a way to pick a random state to enter next).

Page last updated: 2012-10-18



Animation Transitions

Animation Transitions define what happens when you switch from one Animation State to another. There can be only one transition active at any given time.

AtomicIs this transition atomic? (cannot be interrupted)
ConditionsHere we decide when transitions get triggered.

A condition consists of:

You can adjust the transition between the two animation clips by dragging the start and end values of the overlap.

See also Transition solo / mute.

Page last updated: 2012-10-18



Animation Parameters

Animation Parameters are variables that are defined within the animation system but can also be accessed and assigned values from scripts. For example, the value of a parameter can be updated by an animation curve and then accessed from a script so that, say, the pitch of a sound effect can be varied as if it were a piece of animation. Likewise, a script can set parameter values to be picked up by Mecanim. For example, a script can set a parameter to control a Blend Tree.

Default parameter values can be set up using the Parameters widget in the bottom left corner of the Animator window. They can be of four basic types:

Parameters can be assigned values from a script using functions in the Animator class: SetFloat, SetInt, and SetBool.

Here's an example of a script that modifies parameters based on user input

using UnityEngine;
using System.Collections;


public class AvatarCtrl : MonoBehaviour {

	protected Animator animator;

	public float DirectionDampTime = .25f;

	void Start () 
	{
		animator = GetComponent<Animator>();
	}

	void Update () 
	{
		if(animator)
		{
			//get the current state
			AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);

			//if we're in "Run" mode, respond to input for jump, and set the Jump parameter accordingly. 
			if(stateInfo.nameHash == Animator.StringToHash("Base Layer.RunBT"))
			{
				if(Input.GetButton("Fire1")) 
					animator.SetBool("Jump", true );
			}
			else
			{
				animator.SetBool("Jump", false);				
			}

			float h = Input.GetAxis("Horizontal");
			float v = Input.GetAxis("Vertical");

			//set event parameters based on user input
			animator.SetFloat("Speed", h*h+v*v);
			animator.SetFloat("Direction", h, DirectionDampTime, Time.deltaTime);
		}		
	}   		  
}

(back to Animation State Machines)

Page last updated: 2013-10-10



Animation Blend Trees

A common task in game animation is to blend between two or more similar motions. Perhaps the best known example is the blending of walking and running animations according to the character's speed. Another example is a character leaning to the left or right as he turns during a run.

It is important to distinguish between Transitions and Blend Trees. While both are used for creating smooth animation, they are used for different kinds of situations.

Examples of similar motions could be various walk and run animations. In order for the blend to work well, the movements in the clips must take place at the same points in normalized time. For example, walking and running animations can be aligned so that the moments of contact of foot to the floor take place at the same points in normalized time (e.g. the left foot hits at 0.0 and the right foot at 0.5). Since normalized time is used, it doesn't matter if the clips are of different length.

To start working with a new Blend Tree, you need to:

  1. Right-click on empty space on the Animator Controller Window
  2. Select Create State > From New Blend Tree from the context menu that appears.
  3. Double-click on the Blend Tree to enter the Blend Tree Graph.

The Animator Window now shows a graph of the entire Blend Tree while the Inspector shows the currently selected node and its immediate children.

The Animator Window shows a graph of the entire Blend Tree. To the left is a Blend Tree with only the root Blend Node. To the right is a Blend Tree with a root Blend Node and three Animation Clips as child nodes.

This gives a graphical visualization of how the animations are combined as the parameter value changes (as you drag the slider, the arrows from the tree root change their shading to show the dominant animation clip).

You can select any of the nodes in the Blend Tree graph to inspect it in the Inspector. If the selected node is an Animation Clip the Inspector for that Animation Clip will be shown. The settings will be read-only if the animation is imported from a model. If the node is a Blend Node, the Inspector for Blend Nodes will be shown.

A Blend Node shown in the Inspector before any motions have been added.

The Blend Type drop-down is used to select one of the different blend types that can blend according to one or two parameters. You can read more about the different blend types and other Blend Tree options on the following pages.

Page last updated: 2013-01-28



1D Blending

The first option in the Inspector of a Blend Node is the The Blend Type. This drop-down is used to select one of the different blend types that can blend according to one or two parameters. 1D Blending blends the child motions according to a single parameter.

After setting the Blend Type, the first thing you need is to select the Animation Parameter that will control this Blend Tree. In this example, the parameter is direction which varies between -1.0 (left) and +1.0 (right), with 0.0 denoting a straight run without leaning.

Then you can add individual animations by clicking the small "+" button and selecting Add Motion Field from the popup menu. When you're done, it should look something like this:

A 1D Blend Node with three Animation Clips.

The diagram at the top of the Inspector shows the influence of each of the child motions as the parameter varies between its minimum and maximum values. Each motion is shown as a little blue pyramid (the first and last are only shown in half), and if you click and hold down the left mouse button on one them, the corresponding motion is highlighted in the motion list below. The peak of each pyramid defines the parameter value where the motion has full influence, meaning that its animation weight is 1 and the other animations have a weight of 0. This is also called the threshold of the motion.

The diagram at the top of the Blend Node Inspector visualizes the weights of the child motions over the range of the parameter values.

The red vertical bar indicates the value of the Parameter. If you press Play in the Preview at the bottom of the Inspector and drag the red bar in the diagram left and right, you can see how the value of the parameter is controlling the blending of the different motions.

Parameter Range

The range of the parameter used by the Blend Node is shown below the diagram as two numbers to the left and right. Either one of them can be changed by clicking on the number and dragging left or right with the mouse. Note that the values correspond to the threshold of the first and last motion in the motion list.

Thresholds

You can change the threshold value of a motion by clicking on its corresponding blue pyramid in the diagram and dragging it left or right. If the "Automate Thresholds" toggle is not enabled, you can also edit the threshold value of a motion in the motion list by typing in a number in the number field in the Threshold column.

Below the motion list is the checkbox Automate Thresholds. Enabling it will distribute the thresholds of the motions evenly across the parameter range. For example, if there are five clips and the parameter ranges from -90 to +90, the thresholds will be set to -90, -45, 0, +45 and +90 in order.

The Compute Thresholds drop-down will set the thresholds from data of your choice obtained from the root motions in the Animation Clips. The data that is available to choose from is speed, velocity x, y, or z, and angular speed in degrees or radians. If your parameter corresponds to one of these properties, you can compute the thresholds using the Compute Thresholds drop-down.

SpeedSets the threshold of each motion according to its speed (the magnitude of the velocity).
Velocity XSets the threshold of each motion according to its velocity.x.
Velocity YSets the threshold of each motion according to its velocity.y.
Velocity ZSets the threshold of each motion according to its velocity.z.
Angular Speed (Rad)Sets the threshold of each motion according to its angular speed in radians per second.
Angular Speed (Deg)Sets the threshold of each motion according to its angular speed in degrees per second.

Say, for example, you had a walk animation that covered 1.5 units per second, a jog at 2.3 units per second, and a run at 4 units per second, choosing the Speed option from the drop-down would set the parameter range and thresholds for the three animations based on these values. So, if you set the speed parameter to 3.0, it would blend the jog and run with a slight bias toward the jog.

Page last updated: 2013-01-28



2D Blending

The first option in the Inspector of a Blend Node is the The Blend Type. This drop-down is used to select one of the different blend types that can blend according to one or two parameters. The 2D blending types blends the child motions according to two parameters.

The different 2D Blend Types have different uses that they are suitable for. They differ in how the influence of each motion is calculated.

2D Simple Directional
Best used when your motions represent different directions, such as "walk forward", "walk backward", "walk left", and "walk right", or "aim up", "aim down", "aim left", and "aim right". Optionally a single motion at position (0, 0) can be included, such as "idle" or "aim straight". In the Simple Directional type there should not be multiple motions in the same direction, such as "walk forward" and "run forward".
2D Freeform Directional
This blend type is also used when your motions represent different directions, however you can have multiple motions in the same direction, for example "walk forward" and "run forward". In the Freeform Directional type the set of motions should always include a single motion at position (0, 0), such as "idle".
2D Freeform Cartesian
Best used when your motions do not represent different directions. With Freeform Cartesian your X parameter and Y parameter can represent different concepts, such as angular speed and linear speed. An example would be motions such as "walk forward no turn", "run forward no turn", "walk forward turn right", "run forward turn right" etc.

After setting the Blend Type, the first thing you need is to select the two Animation Parameters that will control this Blend Tree. In this example, the parameters are velocityX (strafing) and velocityZ (forward speed).

Then you can add individual animations by clicking + -> Add Motion Field to add an Animation Clip to the blend tree. When you're done, it should look something like this:

A 2D Blend Node with five Animation Clips.

The positions in 2D blending are like the thresholds in 1D blending, except that there are two values instead of one, corresponding to each of the two parameters. Their positions along the horizontal X axis correspond to the first parameter, and their positions along the vertical Y axis correspond to the second parameter. A walking forward animation might have a velocityX of 0 and a velocityZ of 1.5, so those values should be typed into the Pos X and Pos Y number fields for the motion.

The 2D Blending Diagram

The diagram at the top of the Inspector shows the positions of the child motions in the 2D blend space. The motions are shown as blue dots. Motions with no Animation Clip or Blend Tree assigned have no influence on the blend and are shown as gray dots. You can select a motion by clicking on its dot in the diagram. Once selected, the influence of that motion for each point in the blending space is visualized as a blue field. The field is strongest right under the position of the motion, where the motion has full influence, meaning that its animation weight is 1 and the other animations have a weight of 0. Further away the influence decreases as the influence of other motions take over.

The diagram at the top of the Blend Node Inspector visualizes the weights of the child motions over the extends of the parameter values.

The red dot indicates the values of the two Parameters. If you press Play in the Preview at the bottom of the Inspector and drag the red dot in the diagram around, you can see how the values of the parameters are controlling the blending of the different motions. In the diagram you can also see the influence of each motion represented as circles around each motion. You will see that if you move the red dot on top of one of the blue dots representing a motion, the circle for that motion gains its maximum radius and the circles for all other motions shrink down to nothing. At positions that are in between several motions, multiple of the nearby motions will have an influence on the blend. If you select one of the motions in order to see the blue influence field of that motion, you can see that as you move the red dot around, the circle size of the motion corresponds exactly with how strong the influence field is at various positions.

When no motion is selected, the diagram shows a mix of all the influence fields that is more blue where a single motion dominates and less blue where many motions contribute to the blend.

Positions

You can change the positions of a motion by clicking on its corresponding blue dot in the diagram and dragging it around. You can also edit position coordinates of a motion in the motion list by typing in numbers in the number fields in the Pos X and Pos Y columns.

The Compute Positions drop-down will set the positions from data of your choice obtained from the root motions in the Animation Clips. The data that is available to choose from is speed, velocity x, y, or z, and angular speed in degrees or radians. If one or both of your parameters correspond to one of these properties, you can compute the Pos X and/or Pos Y using the Compute Positions drop-down.

Velocity XZSets the Pos X of each motion according to its velocity.x and the Pos Y according to its velocity.z.
Speed And Angular SpeedSets the Pos X of each motion according to its angular speed (in radians per second) and the Pos Y according to its speed.

Furthermore you can mix and match by choosing Compute Position -> X Position From and/or Compute Position -> Y Position From to only auto-compute one of them at a time, leaving the other unchanged.

SpeedSets the Pos X or Pos Y of each motion according to its speed (the magnitude of the velocity).
Velocity XSets the Pos X or Pos Y of each motion according to its velocity.x.
Velocity YSets the Pos X or Pos Y of each motion according to its velocity.y.
Velocity ZSets the Pos X or Pos Y of each motion according to its velocity.z.
Angular Speed (Rad)Sets the Pos X or Pos Y of each motion according to its angular speed in radians per second.
Angular Speed (Deg)Sets the Pos X or Pos Y of each motion according to its angular speed in degrees per second.

Say, for example, that your parameters correspond to sideways velocity and forward velocity, and that you have an idle animation with an average velocity (0, 0, 0), a walk animation with (0, 0, 1.5), and two strafe animations with velocities of (-1.5, 0, 0) and (1.5, 0, 0) respectively. Choosing the Velocity XZ option from the drop-down would set the positions of the motions according to the X and Z coordinates of those velocities.

Page last updated: 2013-01-28



Additional Blend Tree Options

The options below are common to both 1D and 2D blending.

Time Scale

You can alter the "natural" speed of the animation clips using the animation speed number fields (the columns with a clock icon at the top), so you could make the walk twice as fast by using a value of 2.0 as its speed. The Adjust Time Scale > Homogeneous Speed button rescales the speeds of the clips so that they correspond with the chosen minimum and maximum values of the parameter but keep the same relative speeds they initially had.

Note that the Adjust Time Scale drop-down is only available if all the motions are Animation Clips and not child Blend Trees.

Mirroring

You can mirror any humanoid Animation Clip in the motions list by enabling the mirror toggle at the far right. This feature enables you to use the same animation in its original form and in a mirrored version without needing twice the memory and space.

Page last updated: 2013-01-28



Advanced topics

The following section covers the features Mecanim provides for controlling and managing complex sets of animations.

(back to Mecanim introduction)

Page last updated: 2012-11-08



Animation Curves in Mecanim

Animation curves can be attached to animation clips in the Animations tab of the Animation Import Settings.

The curves on animation clips in Mecanim

The curve's X-axis represents normalized time and always ranges between 0.0 and 1.0 (corresponding to the beginning and the end of the animation clip respectively, regardless of its duration).

Unity Curve Editor

Double-clicking an animation curve will bring up the standard Unity curve editor (see Editing Value Properties for further details) which you can use to add keys to the curve. Keys are points along the curve's timeline where it has a value explicitly set by the animator rather than just using an interpolated value. Keys are very useful for marking important points along the timeline of the animation. For example, with a walking animation, you might use keys to mark the points where the left foot is on the ground, then both feet on the ground, right foot on the ground, etc. Once the keys are set up, you can move conveniently between key frames by pressing the Previous/Next Key Frame buttons. This will move the vertical red line and show the normalized time at the keyframe; the value you enter in the text box will then set the value of the curve at that time.

Animation Curves and Animator Controller parameters

If you have a curve with the same name as one of the parameters in the Animator Controller, then that parameter will take its value from the value of the curve at each point in the timeline. For example, if you make a call to GetFloat from a script, the returned value will be equal to the value of the curve at the time the call is made. Note that at any given point in time, there might be multiple animation clips attempting to set the same parameter from the same controller. In that case, the curve values from the multiple animation clips are blended. If an animation has no curve for a particular parameter then the blending will be done with the default value for that parameter.

(back to Mecanim introduction)

Page last updated: 2012-11-08



Nested State Machines

It is common for a character to have complex actions that consist of a number of stages. Rather than handle the entire action with a single state, it makes sense to identify the separate stages and use a separate state for each. For example, a character may have an action called "Trickshot" where it crouches to take a steady aim, shoots and then stands up again.


The sequence of states in a "Trickshot" action

Although this is useful for control purposes, the downside is that the state machine will become large and unwieldy as more of these complex actions are added. You can simplify things somewhat just by separating the groups of states visually with empty space in the editor. However, Mecanim goes a step further than this by allowing you to collapse a group of states into a single named item in the state machine diagram. These collapsed groups of states are called Sub-state machines.

You can create a sub-state machine by right clicking on an empty space within the Animator Controller window and selecting Create Sub-State Machine from the context menu. A sub-state machine is represented in the editor by an elongated hexagon to distinguish it from normal states.


A sub-state machine

When you double-click the hexagon, the editor is cleared to let you edit the sub-state machine as though it were a completely separate state machine in its own right. The bar at the top of the window shows a "breadcrumb trail" to show which sub-state machine is currently being edited (and note that you can create sub-state machines within other sub-state machines, and so on). Clicking an item in the trail will focus the editor on that particular sub-state machine.


The "breadcrumb trail"

External transitions

As noted above, a sub-state machine is just a way of visually collapsing a group of states in the editor, so when you make a transition to a sub-state machine, you have to choose which of its states you want to connect to.


Choosing a target state within the "Trickshot" sub-state machine

You will notice an extra state in the sub-state machine whose name begins with Up.


The "Up" state

The Up state represents the "outside world", the state machine that encloses the sub-state machine in the view. If you add a transition from a state in sub-state machine to the Up state, you will be prompted to choose one of the states of the enclosing machine to connect to.


Connecting to a state in the enclosing machine

(back to State Machines introduction)

(back to Mecanim introduction)

Page last updated: 2012-11-07



Animation Layers

Unity uses Animation Layers for managing complex state machines for different body parts. An example of this is if you have a lower-body layer for walking-jumping, and an upper-body layer for throwing objects / shooting.

You can manage animation layers from the Layers Widget in the top-left corner of the Animator Controller.

You can add a new layer by pressing the + on the widget. On each layer, you can specify the body mask (the part of the body on which the animation would be applied), and the Blending type. Override means information from other layers will be ignored, while Additive means that the animation will be added on top of previous layers.

The Mask property is there to specify the body mask used on this layer. For example if you want to use upper body throwing animations, while having your character walk or run, you would use an upper body mask, like this:

For more on Avatar Body Masks, you can read this section

Animation Layer syncing (Pro only)

Sometimes it is useful to be able to re-use the same state machine in different layers. For example if you want to simulate "wounded" behavior, and have "wounded" animations for walk / run / jump instead of the "healthy" ones. You can click the Sync checkbox on one of your layers, and then select the layer you want to sync with. The state machine structure will then be the same, but the actual animation clips used by the states will be distinct.

(back to Mecanim introduction)

Page last updated: 2012-11-06



Animation State Machine Preview (solo and mute)

Solo and Mute functionality

In complex state machines, it is useful to preview the operation of some parts of the machine separately. For this, you can use the Mute / Solo functionality. Muting means a transition will be disabled. Soloed transtions are enabled and with respect to other transitions originating from the same state. You can set up mute and solo states either from the Transition Inspector, or the State Inspector (recommended), where you'll have an overview of all the transitions from that state.

Soloed transitions will be shown in green, while muted transitions in red, like this:

In the example above, if you are in State 0, only transitions to State A and State B will be available.

Known issues:

(back to State Machines introduction)

(back to Mecanim introduction)

Page last updated: 2012-10-08



Target Matching

Often in games, a situation arises where a character must move in such a way that a hand or foot lands at a certain place at a certain time. For example, the character may need to jump across stepping stones or jump and grab an overhead beam.

You can use the Animator.MatchTarget function to handle this kind of situation. Imagine, for example, you want to arrange an situation where the character jumps onto a platform and you already have an animation clip for it called Jump Up. Firstly, you need to find the place in the animation clip at which the character is beginning to get off the ground, note in this case it is 14.1% or 0.141 into the animation clip in normalized time:-

You also need to find the place in the animation clip where the character is about to land on his feet, which in this case is at 78.0% or 0.78.

With this information, you can create a script that calls MatchTarget which you can attach to the model:-

using UnityEngine;
using System;

[RequireComponent(typeof(Animator))]  
public class TargetCtrl : MonoBehaviour {

	protected Animator animator;	

	//the platform object in the scene
	public Transform jumpTarget = null; 
	void Start () {
		animator = GetComponent<Animator>();
	}

	void Update () {
		if(animator) {
			if(Input.GetButton("Fire1"))		       
				animator.MatchTarget(jumpTarget.position, jumpTarget.rotation, AvatarTarget.LeftFoot, 
                                                       new MatchTargetWeightMask(Vector3.one, 1f), 0.141f, 0.78f);
		}		
	}
}

The script will move the character so that it jumps from its current position and lands with its left foot at the target. Bear in mind that the result of using MatchTarget will generally only make sense if it is called at the right point in gameplay.

(back to Mecanim introduction)

Page last updated: 2013-10-10



Root Motion

Body Transform

The Body Transform is the mass center of the character. It is used in Mecanim's retargeting engine and provides the most stable displacement model. The Body Orientation is an average of the lower and upper body orientation relative to the Avatar T-Pose.

The Body Transform and Orientation are stored in the Animation Clip (using the Muscle definitions set up in the Avatar). They are the only world-space curves stored in the Animation Clip. Everything else: muscle curves and IK goals (Hands and Feet) are stored relative to the body transform.

Root Transform

The Root Transform is a projection on the Y plane of the Body Transform and is computed at runtime. At every frame, a change in the Root Transform is computed. This change in transform is then applied to the Game Object to make it move.

The circle below the character represents the root transform

Animation Clip Inspector

The Animation Clip Editor settings (Root Transform Rotation, Root Transform Position (Y) and Root Transform Position (XZ)) let you control the Root Transform projection from the Body Transform. Depending on these settings some parts of the Body Transform may be transferred Root Transform. For example you can decide if you want the motion Y position to be part of the Root Motion (trajectory) or part of the pose (body transform), which is known as Baked into Pose.

Root Transform Rotation

Bake into Pose: The orientation will stay on the body transform (or Pose). The Root Orientation will be constant and delta Orientation will be identity. This means the the Game Object will not be rotated at all by that AnimationClip.

Only AnimationClips that have similar start and stop Root Orientation should use this option. You will have a Green Light in the UI telling you that an AnimationClip is a good candidate. A suitable candidate would be a straight walk or a run.

Based Upon: This let you set the orientation of the clip. Using Body Orientation, the clip will be oriented to follow the forward vector of body. This default setting works well for most Motion Capture (Mocap) data like walks, runs, and jumps, but it will fail with motion like strafing where the motion is perpendicular to the body's forward vector. In those cases you can manually adjust the orientation using the Offset setting. Finally you have Original that will automatically add the authored offset found in the imported clip. It is usually used with Keyframed data to respect orientation that was set by the artist.

Offset: used to enter the offset when that option is chosen for Based Upon.

Root Transform Position (Y)

This uses the same concepts described in Root Transform Rotation.

Bake Into Pose: The Y component of the motion will stay on the Body Transform (Pose). The Y component of the Root Transform will be constant and Delta Root Position Y will be 0. This means that this clip won't change the Game Object Height. Again you have a Green Light telling you that a clip is a good candidate for baking Y motion into pose.

Most of the AnimationClips will enable this setting. Only clips that will change the GameObject height should have this turned off, like jump up or down.

Note: the Animator.gravityWeight is driven by Bake Into Pose position Y. When enabled, gravityWeight = 1, when disable = 0. gravityWeight is blended for clips when transitioning between states.

Based Upon: In a similar way to Root Transform Rotation you can choose from Original or Mass Center (Body). There is also a Feet option that is very convenient for AnimationClips that change height (Bake Into Pose disabled). When using Feet the Root Transform Position Y will match the lowest foot Y for all frames. Thus the blending point always remains around the feet which prevents floating problem when blending or transitioning.

Offset: In a similar way to Root Transform Rotation, you can manually adjust the AnimationClip height using the Offset setting.

Root Transform Position (XZ)

Again, this uses same concepts described in Root Transform Rotation and Root Motion Position (Y).

Bake Into Pose will usually be used for "Idles" where you want to force the delta Position (XZ) to be 0. It will stop the accumulation of small deltas drifting after many evaluations. It can also be used for a Keyframed clip with Based Upon Original to force an authored position that was set by the artist.

Loop Pose

Loop Pose (like Pose Blending in Blend Trees or Transitions) happens in the referential of Root Transform. Once the Root Transform is computed, the Pose becomes relative to it. The relative Pose difference between Start and Stop frame is computed and distributed over the range of the clip from 0-100%.

Generic Root Motion and Loop Pose.

This works in essentially the same as Humanoid Root Motion, but instead of using the Body Transform to compute/project a Root Transform, the transform set in Root Node is used. The Pose (all the bones which transform below the Root Motion bone) is made relative to the Root Transform.

Page last updated: 2013-04-22



Scripting Root Motion

Sometimes your animation comes as "in-place", which means if you put it in a scene, it will not move the character that it's on. In other words, the animation does not contain "root motion". For this, we can modify root motion from script. To put everything together follow the steps below (note there are many variations of achieving the same result, this is just one recipe).

Finally, to control the motion, we will need to create a script (RootMotionScript.cs), that implements the OnAnimatorMove callback:-

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Animator))]

public class RootMotionScript : MonoBehaviour {

	void OnAnimatorMove()
	{
            Animator animator = GetComponent<Animator>(); 

            if (animator)
            {
	       Vector3 newPosition = transform.position;
               newPosition.z += animator.GetFloat("Runspeed") * Time.deltaTime;                                 
	       transform.position = newPosition;
            }
	}
}

You should attach RootMotionScript.cs to the "Dude" object. When you do this, the Animator component will detect that the script has an OnAnimatorMove function and show the Apply Root Motion property as Handled by Script

(back to Mecanim introduction)

Page last updated: 2013-10-10



Mecanim Peformance and Optimization

This page contains some tips to help you obtain the best performance from Mecanim, covering character setup, the animation system and runtime optimizations.

Character Setup

Number of Bones

In some cases you will need to create characters with a large number of bones, for example when you want a lot of customizable attachments. These extra bones will increase the size of the build, and you could expect to have a relative processing cost for each additional bone. For example, 15 additional bones on a rig that already has 30 bones will take 50% longer to solve in Generic mode. Note that you can have additional bones in Generic and in Humanoid mode. When you have no animations playing using the additional bones, the processing cost should be negligible. This cost will be even lower if their attachments are non existent or hidden.

Multiple Skinned Meshes

Combine skinned meshes whenever possible. Splitting a character into two Skinned Mesh Renderers is a bad idea with regard to performance. It's better if your character has just one material, but there are some cases when you might require more materials.

Animation System

Controllers

The Animator doesn't spend time processing when a Controller is not set to it.

Simple Animation

Playing a single Animation Clip with no blending can make Mecanim slower than the legacy animation system. The old system is very direct, sampling the curve and directly writing into the transform. Mecanim has temporary buffers it uses for blending, and there is additional copying of the sampled curve and other data. The Mecanim layout is optimized for animation blending and more complex setups.

Scale Curves

Make sure that there is not a single scale curve on any animation clip. You can write an asset post-processor to remove or warn about them; see the AssetPostprocessor reference for more information.

Layers

Most of the time Mecanim is evaluating animations, and the overhead for AnimationLayers and AnimationStateMachines is kept to the minimum. The cost of adding another layer to the animator, synchronized or not, depends on what animations and blend trees are played by the layer. When the weight of the layer is zero, the layer update will be skipped.

Humanoid vs. Generic Modes

These tips will help you decide between these modes:

Mecanim Scene

There are many optimizations that can be made, some useful tips include:

Runtime Optimizations

Visibility and Updates

Always optimize animations by setting the animators's Culling Mode to Based on Renderers, and disable the skinned mesh renderer's Update When Offscreen property. This way animations won't be updated when the character is not visible. See the skinned mesh renderer for further information.

Page last updated: 2013-07-18



Mecanim FAQ

General questions

We are using the legacy animation system for character animations. Should use Mecanim instead?

Mecanim is the main animation technology that will be used and developed by Unity from now on. The legacy system will not be updated significantly.

Import

Why is an Animator added automatically to every mesh as it is imported?

Currently there is no way for you to change the default import settings but if you set the Rig to None in the import settings then the Animator component will not be added - you can do this with several files at once

Layers

Does the ordering of the layers matter?

Yes. Layers are evaluated from top to bottom in order. Layers set to override will always override the previous layers (based on their mask, if they have a mask)

Is the base layer weight always supposed to be one or should the weight be set to zero when another synced layer is run?

The base layer weight is always 1 but layers set to override will completely override the base layer.

What happens if a synced layer has a different length to the corresponding state in the base layer?

If layers have different lengths then they will become unsynchronised.

Is there any way to get a variable value from the controller without using the name string?

You can use integers to identify the states and parameters. Use the Animator.StringToHash function to get the integer identifier values. For example:

runState = Animator.StringToHash("Base Layer.Run");
animator.SetBool(runState, false);

Avatars and body Masks

Is there a way to define what bones should be part of a body mask?

Due to implementation details, this is currently not possible.

Is there a way to create AvatarIKGoals other than LeftFoot, RightFoot, LeftHand, RightHand?

This feature is planned for a future release.

Animations curves and events

Can you add animation events to Mecanim?

This is high in our priorities for future development. For the time being, we suggest using additional animation curves to simulate events approximately. Although this technique doesn't recreate events exactly, many of our users have reported it as useful.

How do animations that have Curves blend with those that don't?

When you have an animation with a curve and another animation without a curve, Unity will use the default value of the parameter connected to the curve to do blending. You can set default values for your parameters, so when blending takes place between a State that has a Curve Parameter and one that does not have one, it will blend between the curve value and the default parameter value. To set a default value for a Parameter, simply set its value in the Animator Tool window while not in LiveLink.

Page last updated: 2013-04-23



AnimationView43

The Animation View lets you preview and edit Animation Clips for animated Game Objects in Unity. This section gives full details of how to work with the view in your project.

Page last updated: 2013-11-04



UsingAnimationView

When you open the Animation View (menu: Window > Animation), you will see a window similar to this:

The Animation View is tightly integrated with the Hierarchy View, the Scene View, and the Inspector. Like the Inspector, the Animation View will show whatever Game Object is selected. You can select a Game Object to view using the Hierarchy View or the Scene View. (If you select a Prefab in the Project View you can inspect its animations as well, but you have to drag the Prefab into the Scene View in order to be able to edit them.)

At the left side of the Animation View is a list of the animated properties of the selected Game Object. Properties can be folded and unfolded by clicking the foldout triangles next to them.

Creating a New Animation Clip

Animated Game Objects in Unity need an Animator Component that controls the animations. If a Game Object doesn't already have an Animator Component, the Animation View will add one for you automatically when creating a new Animation Clip or when entering Animation Mode. To create a new Animation Clip for the selected Game Object, click the selection box at the upper left of the Animation View and select [Create New Clip]. You will then be prompted to save an Animation Clip somewhere in your Assets folder. If the Game Object doesn't have an Animator Component already, it will be automatically added at this point. The new Animation Clip will automatically be added to the Animator.

To begin editing an Animation Clip for the selected Game Object, click on the Animation Mode button (the red "Record" button next to the "Play" button in the animation view toolbar).

This will enter Animation Mode, where changes to the Game Object are stored into the Animation Clip. (If the Game Object doesn't have an Animator Component already, it will be automatically added at this point. If there is not an existing Animation Clip, you will be prompted to save one somewhere in your Assets folder.)

You can stop the Animation Mode at any time by clicking the Animation Mode button again. This will revert the Game Object to the state it was in prior to entering the Animation Mode.

To animate a property, click on the Add Curve button and choose the property from the popup list.

Transform properties are special in that the .x, .y, and .z properties are linked, so those curves are added three at a time. See the section on Using Animation Curves for further information.

When in Animation Mode, a red vertical line will show which frame of the Animation Clip is currently previewed. The Inspector and Scene View will show the Game Object at that frame of the Animation Clip. The values of the animated properties at that frame are also shown in a column to the right of the property names.

You can click anywhere on the Time Line to preview or modify that frame in the Animation Clip. The numbers in the Time Line are shown as seconds and frames, so 1:30 means 1 second and 30 frames.

You can go directly to a specific frame by typing it in, or use the buttons to go to the previous or next keyframe.

You can also use the following keyboard shortcuts to navigate between frames:

In Animation Mode you can move, rotate, or scale the Game Object in the Scene View. This will automatically create Animation Curves for the position, rotation and scale properties of the Animation Clip if they didn't already exist, and keys on those Animation Curves will automatically be created at the currently previewed frame to store the respective Transform values you changed.

You can also use the Inspector to modify any of the animatable properties of the Game Object. This too will create Animation Curves as needed, and create keys on those Animation Curves at the currently previewed frame to store your changed values. Properties that are not animatable are grayed out in the Inspector while in Animation Mode.

The Keyframe button creates a keyframe for the shown curves at the currently previewed frame (shortcut: K).

You can also manually create a keyframe using the Keyframe button. This will create a key for all the curves that are currently selected in the Animation View.

When you press the keyframe button, a new keyframe is added to the currently selected properties.

Creating Sprite Animations

There are several ways to create a sprite animation. The easiest is to drag and drop selected sprites from the Project View to the Hierarchy or Scene View in 2D mode. This will create a new Animation Clip and a Game Object with Sprite Renderer and Animator components added.

You can also add a new Animation Clip to a Game Object with an Animation component. One Animator can contain multiple Animation Clips. See the section of the manual about the Mecanim animation system to see how to make transitions between different Animation Clips.

A third way to create new sprite animations is to add new Sprite Frames to an existing Animation Clip. You can drag and drop Sprites from the Project View to the expanded SpriteRenderer.Sprite property in the Dopesheet View

For further details of how to slice existing sprite sheets into single Sprites see the Sprite Editor manual page.

Playback

The Animation Clip can be played back at anytime by clicking the Play button in the Animation View toolbar.

Page last updated: 2013-11-04



UsingDopesheet

In the Animation View, animated properties will be shown with diamond shaped keys. These are control points that specify how the property should be animated. A frame that has a key is called a keyframe.

Keyframes can be dragged around with the mouse. It is also possible to select multiple keyframes at once by dragging a rectangular selection around them all.

You can add a keyframe by double clicking on the empty space in the dopesheet. Alternatively, you can use the context menu or click the keyframe button which will add keyframes to the currently previewed frame on the selected properties. Keyframes can be deleted by selecting them and pressing Delete or by right-clicking on them and selecting Delete Keyframe from the context menu.

Navigating the Dopesheet

When working with the Animation View you can easily zoom in on the details of the curves you want to work with or zoom out to get the full picture.

You can always press F to zoom to the full clip or to selected keys.

You can zoom the Dopesheet View using the scroll-wheel of your mouse, the zoom functionality of your trackpad, or by holding Alt while right-dragging with your mouse. You can zoom on only the horizontal axis. You can also drag the end caps of the scrollbars to shrink or expand the area shown in the Dopesheet View.

You can pan the Curve View by middle-dragging with your mouse or by holding Alt while left-dragging with your mouse.

Editing Tangents

A key has two tangents - one on the left for the ingoing slope and one on the right for the outgoing slope. The tangents control the shape of the curve between the keys. The Animation View have multiple tangent types that can be used to easily control the curve shape. The tangent types for a key can be chosen by right-clicking the key.

Objects with Multiple Moving Parts

You may want to animate Game Objects that have multiple moving parts, such as a gun turret with a moving barrel, or a character with many body parts. All the parts can be animated by a single Animator component on the parent.

You can add animated properties for child objects from the Add Curve popup menu, or by changing the values from inspector while in record mode.

In the Add Curve popup, you can access the properties of a child object by using the foldout triangle next to the object's name. The properties of child objects can be animated just like those of the parent.

Page last updated: 2013-11-04



UsingAnimEvents

The power of animation clips can be increased further by using Animation Events. These allow you to call functions in the object's script at specified points in the timeline. The function called by an animation event can optionally take one parameter which can be a float, string, int, object reference or an AnimationEvent object. The AnimationEvent object has member variables that allow a float, string, integer and object reference to be passed into the function all at once, along with other information about the event that triggered the function call.

// This JavaScript function can be called by an Animation Event
function PrintFloat (theValue : float) {
	Debug.Log ("PrintFloat is called with a value of " + theValue);
}

You can add an animation event to a clip at the current playhead position by clicking the Event button or at any point in the animation by double-clicking the Event Line at the point where you want the event to be triggered. Once added, an event can be repositioned by dragging with the mouse. You can delete an event by selecting it and pressingDelete, or by right-clicking on it and selecting Delete Event from the contextual menu.

When you add an event, a dialog box will appear to prompt you for the name of the function and the value of the parameter you want to pass to it.

The Animation Event popup dialog lets you specify which function to call with which parameter value. The events added to a clip are shown as markers in the event line. Holding the mouse over a marker will show a tooltip with the function name and parameter value.

Page last updated: 2013-11-04



UsingAnimCurves

Any property that can be animated can have an Animation Curve to allow it to be controlled from an animation clip. In the property list, the Animation View properties with Animation Curves have colored curve indicators. For information on how to add curves to an animation property, see the page about Using the Animation View.

By default, the Animation Window will show the Dopesheet view instead of the Curves. Click the Curves button at the bottom left of the window to change to the Curve view.

Only selected properties with animation curves will be shown in the right side of the view.

Understanding Curves, Keys and Keyframes

An Animation Curve has multiple keys which act as control points that the curve passes through. These are visualized in the Curve Editor as small diamond shapes on the curves. A frame in which one or more of the shown curves have a key is called a keyframe. If a property has a key in the currently previewed frame, the curve indicator will have a diamond shape.

A keyframe can be added at the currently previewed frame by clicking the Keyframe button. This will add a key to all the selected properties at once. It is also possible to add a keyframe by right-clicking the Keyframe Line and select Add Keyframe from the context menu. Once placed, keyframes can be dragged around with the mouse. It is also possible to select multiple keyframes to drag at once. Keyframes can be deleted by selecting them and pressing Delete, or by right-clicking on them and selecting Delete Keyframe from the context menu.

Property Types that Support Animation

The Animation View can be used to animate much more than just the position, rotation and scale of a Game Object. The properties of any Component and Material can be animated, including the public variables of your own script components. Making animations with complex visual effects and behaviors is a simple matter of adding Animation Curves for the relevant properties.

The following types of properties are supported in the animation system:

Arrays are not supported and neither are structs or objects other than the ones listed above.

Here are a few examples of the many things the Animation View can be used for:-

When using Animation Curves to control game logic, please be aware of the way animations are played back and sampled in Unity.

Rotation Interpolation Types

In Unity rotations are internally represented as Quaternions. Quaternions consist of .x, .y, .z, and .w values that should generally not be modified manually except by people who know exactly what they're doing. Instead, rotations are typically manipulated using Euler Angles which have .x, .y, and .z values representing the rotations around those three respective axes.

When interpolating between two rotations, the interpolation can either be performed on the Quaternion values or on the Euler Angles values. The Animation View lets you choose which form of interpolation to use when animating Transform rotations. However, the rotations are always shown in the form of Euler Angle values regardless of which interpolation form is selected.

Quaternion Interpolation

Quaternion interpolation always generates nice interpolations along the shortest path between two rotations. This avoids rotation interpolation artifacts such as Gimbal Lock. However, Quaternion interpolation cannot represent rotations larger than 180 degrees, because it is then shorter to go the other way around. If you use Quaternion interpolation and place two keys further apart than 180 degrees, the curve will look discontinuous, even though the actual rotation is still smooth - it simply goes the other way around, because it is shorter. If rotations larger than 180 degrees are desired, additional keys must be placed in between. When using Quaternion interpolation, changing the keys or tangents of one curve may also change the shapes of the other two curves, since all three curves are created from the internal Quaternion representation. When using Quaternion interpolation, keys are always linked, so that creating a key at a specific time for one of the three curves will also create a key at that time for the other two curves.

Placing two keys 270 degrees apart when using Quaternion interpolation will cause the interpolated value to go the other way around, which is only 90 degrees.

Euler Angles Interpolation

Euler Angles interpolation is what most people are used to working with. Euler Angles can represent arbitrary large rotations and the .x, .y, and .z curves are independent from each other. Euler Angles interpolation can be subject to artifacts such as Gimbal Lock when rotating around multiple axes at the same time, but are intuitive to work with for simple rotations around one axis at a time. When Euler Angles interpolation is used, Unity internally bakes the curves into the Quaternion representation used internally. This is similar to what happens when importing animation into Unity from external programs. Note that this curve baking may add extra keys in the process and that tangents with the Constant tangent type may not be completely precise at a sub-frame level.

Page last updated: 2013-11-04



Navmesh and Pathfinding

In many games, a character needs to be able to travel automatically from its current position to a desired destination. For example, you might control a player character by clicking on a target point in the game world, or perhaps an NPC enemy might need to find a route to intercept the player. In some cases, this will be a simple matter of moving in a straight line or along a preset path but there are also game worlds based around buildings, forests or other settings where the route to the target is not so direct. In games like these, some control logic is needed to allow the character to make decisions at each point along its journey to choose its next step. The process of choosing a character's movements around the game world like this is known as navigation.

There are various techniques that can be used to navigate a character to its destination, some of which involve an element of trial and error with mistakes and wrong turnings. Often though, the desired behaviour is to make the character appear to be planning its path intelligently, taking the most direct or advantageous route. This requires a bit of artificial intelligence (AI) to establish the best way to get from the starting point to the destination. This task in game AI is known as pathfinding and although it can be quite technical, Unity makes some common cases very easy using its built-in pathfinding system. This section describes Unity's navigation and pathfinding in detail.

Page last updated: 2013-10-04



Navmeshes

A pathfinding system needs a way to represent which parts of the game world can be reached by a character and also a way to determine the possible routes between any two points and choose the best. A mesh (similar to the ones used for 3D graphics) is a good solution to both problems. The reachable area is defined by the polygons of the mesh, while the possible paths through the mesh are conveniently broken down into hops between adjacent polygons. In theory, the same mesh that is used for the floor graphics can also be used for navigation. In practice, the graphical mesh is usually too detailed and consequently inefficient for navigation. For this and other reasons, an AI system usually supplements the floor mesh with a simpler, invisible mesh known as a navigation mesh (or "navmesh" for short). Fortunately, there are techniques to generate an efficient navmesh automatically from a graphical floor mesh and a few numeric parameters. The process of computing a navmesh in this way is known as baking.

In Unity, navmesh generation is handled from the Navigation window (menu: Window > Navigation). If you select the Object tab in the window, you will see something like the following:-

The Scene Filter options simply restrict the selection of objects shown in the Scene view and Hierarchy panel. The other options apply to the selected scene object(s); broadly, they allow you to include or exclude an object within the walkable area of the navmesh. You should mark objects to be included in the navmesh as Navigation Static. You can then set the Navigation Layer to Default if you want the area to be walkable or to Not Walkable otherwise. Typically, the walkable areas correspond to floors, ramps and bridges in the game world, while non-walkable areas correspond to walls and other impassable obstacles.

The Bake button gives you further options for navmesh generation on a separate panel:-

Of particular note are the General settings. The Radius determines how close a navigating character can get to a wall and consequently the width of the narrowest gap between two walls that can it can squeeze through. The Height refers to the height of the "ceiling" above the navmesh surface - an area may not be reachable simply because there is not enough headroom for the character. The Max Slope parameter sets the threshold of steepness where a ramp becomes a wall while the Step Height is the maximum height of bump or step in the floor surface that is ignored by the character (any step greater than this height results in a disconnected walkable area rather than a continuation of the same area).

With these parameters set, you can click the Bake button to compute the navmesh. The baking usually takes place very quickly and the resulting navmesh will be shown in the Scene as an overlay on the underlying level geometry. You may need a few attempts based on what you see in the scene before you get the settings for the navmesh just right.

Page last updated: 2013-10-04



EnablingCharToNavigate

Once the navmesh is set up, the characters need to be equipped to use it. The Nav Mesh Agent component handles both the pathfinding and the movement control of a character. In your scripts, navigation can be as simple as setting the desired destination point - the Nav Mesh Agent can handle everything from there on.

You can add a Nav Mesh Agent component either from a script or from the editor (menu: Component > Navigation > Nav Mesh Agent). The component has a number of properties that are explained fully in the Nav Mesh Agent component reference page, but the default values usually work well as a base for experimentation.

In your script, you will need to get a reference to the NavMeshAgent component since there is no property to access it directly:-

var agent: NavMeshAgent = GetComponent.<NavMeshAgent>();

Then, to set the character in motion, you just need a single call to SetDestination:-

agent.SetDestination(targetPoint);

The target point is specified as a point in world space; the navigation system will find the closest point on the navmesh automatically, so it doesn't matter if the target point is not precisely on the mesh surface.

Naturally, the navigation system can't handle every aspect of the game logic, so you need to have some method of choosing the appropriate destination point in the first place. This task depends heavily on the nature of the gameplay but some common situations include

Page last updated: 2013-10-04



OffMeshLinks

In general, the walkable floor area of a game world will not be limited to just a single mesh. For design purposes, it is often easier to break a floor surface up into a number of separate sections even if the floor is continuous. Also, you may want to allow a character to walk between two points on a playing area but only by passing through a "bottleneck" feature (eg, crossing a river only at a narrow bridge). For these and other purposes, Unity allows you to connect two navmeshes together using off-mesh links.

An off-mesh link has two end points, one on each of the two meshes that are to be connected. When a agent needs to cross between two linked navmeshes, it will head for the endpoint of the nearest link between the two. It will then traverse the link to the endpoint on the other navmesh. Its journey then continues to the destination as normal. By default, off-mesh links are traversed automatically but you can also enable your script to detect when an agent reaches a link and optionally deny it passage. This can be useful for simulating something like a locked door which can be passed but only when the character has the right key.

Adding Off-mesh Links During Baking

Links can easily be added automatically during the mesh baking process. To enable this, you should first select Off Mesh Link Generation for all required navmesh objects in the Object tab of the Navigation window:-

If you then switch to the Baking tab, you will see a section entitled Generated Off Mesh Links. The Drop Height and Jump Distance properties represent the maximum vertical and horzontal distance that can be bridged by a link between the two meshes. When you click the Bake button, you should see in the Scene view that all meshes within the allowed drop height and jump distance are connected by arched black lines. These lines represent the links between the meshes. A navmesh agent on one mesh will now be able to reach a target point on a separate mesh by following any available link between the two.

Note that you can restrict link generation so that links can only be crossed in one direction but not the reverse. If you have the Off Mesh Link Generation option set for mesh A (in the Navigation window's Object panel) but not for mesh B then links going from A to B will be generated but links going from B to A will not. This is useful for simulating something like a high ledge where the character can fall off but then can't climb back up again.

Adding Off-mesh Links Manually

In some cases, two navmeshes should be connected wherever their edges overlap. This typically happens when the two meshes represent a single surface that includes a step or gap. Sometimes though, links can be positioned specifically to enable a situation in the game. For example, a single link can be placed to represent a doorway, bridge or other narrow point of contact between two separate sections of the playing area. Furthermore, it will often help with pathfinding performance on a large game world if that world is broken down into separate navmeshes with only a few limited points of contact between them. The automatic link generation won't be able to places links judiciously like this but you can add your own links between meshes manually using the Off Mesh Link component.

An Off Mesh Link component can be added to any available object (menu: Component > Navigation > Off Mesh Link). Full details are given on the component reference page but the main properties are Start and End; these specify object Transforms that mark the start and end positions of the link and it is often convenient to add the Off Mesh Link component to one of these objects. The anchor points of these marker objects need to be placed quite close to the surface of the navmesh for the link to be enabled. When the endpoints are correctly placed, you will see the link line appear in the Scene view as long as the Navigation window is selected at the time.

Page last updated: 2013-10-04



NavLayersAndCosts

To create the appearance of "intelligent" agents, the pathfinding system is designed to search for the optimal path from the starting point to the destination. As a general rule the shortest path is considered optimal, but there are many situations in real life where the calculation is not quite so simple. For example, the shortest route between two points might be covered in thick snow and so it could be quicker to walk along a cleared footpath even if the journey was longer. There may be concerns other than time too. At night, you might prefer to avoid walking down a dark alleyway and take a longer but well-lit route for safety. You can understand both these situations by noting that each step along a path has a certain cost associated with it. The cost could represent the difficulty of the terrain, risk or many other factors you might bear in mind when planning a route. The optimal route is therefore the one with the lowest overall cost and this will not always be the shortest.

In Unity, each navmesh section can be set up with a cost value through the use of Navmesh Layers. If you select the Layers tab of the Navigation window, you will see a list of thirty-two available layers, three of which are "built-in" layers reserved by Unity. When you open a foldout for one of the User Layers, you will see that you can assign it with a name and a cost value.

If you now go to the Object tab, and look on the Navigation Layer popup, you can see any user layers you have assigned on the menu. By choosing a layer for a navmesh object, you are also assigning the cost for each unit of distance an agent travels over it. This enables a level designer to divide a scene up into separate navmeshes representing differing traversal costs.

Tips and Use Cases for Costs

An important thing to bear in mind when using costs is that a long journey over low-cost ground can be more expensive than a short journey over high-cost ground. Sometimes this will give plausible behaviour, for example when a character risks a shortcut down a dark alleyway rather than a very long round trip. However, the behaviour might sometimes be "rational" but unrealistic. A car can be made to favour roads by assigning them a low cost, but it should never normally drive through somebody's garden just to avoid a hairpin bend. Careful choice and testing of costs is sometimes necessary and it might be easier to redesign a level slightly rather than juggle with a complex setup of different navmesh costs.

In some situations, most of the ground will be "normal" but there might be some areas that are advantageous to cross. For example, it might be preferable to take a moving walkway or a slide rather than walk the same distance. It is fine to set the cost less than the default value of one for cases like this but you should not attempt to use negative costs to indicate advantages. Since the agent is trying to find the lowest-cost path, he might spend a long time wandering aimlessly around an area of negative cost given that each step actually reduces the cost of the path overall. If you want your game to have mostly normal areas but occasionally have advantageous ground then the best solution is to use a cost greater than one for the "normal" layer and a lower cost for the "advantage" layer.

The cost of a path is a very abstract concept and could involve many different factors but some possible use cases include:-

Page last updated: 2013-10-04



Sound

Audio Listener

The Audio Listener acts as a microphone-like device. It receives input from any given Audio Source in the scene and plays sounds through the computer speakers. For most applications it makes the most sense to attach the listener to the Main Camera. If an audio listener is within the boundaries of a Reverb Zone reverberation is applied to all audible sounds in the scene. (PRO only) Furthermore, Audio Effects can be applied to the listener and it will be applied to all audible sounds in the scene.


The Audio Listener, attached to the Main Camera

Properties

The Audio Listener has no properties. It simply must be added to work. It is always added to the Main Camera by default.

Details

The Audio Listener works in conjunction with Audio Sources, allowing you to create the aural experience for your games. When the Audio Listener is attached to a GameObject in your scene, any Sources that are close enough to the Listener will be picked up and output to the computer's speakers. Each scene can only have 1 Audio Listener to work properly.

If the Sources are 3D (see import settings in Audio Clip), the Listener will emulate position, velocity and orientation of the sound in the 3D world (You can tweak attenuation and 3D/2D behavior in great detail in Audio Source) . 2D will ignore any 3D processing. For example, if your character walks off a street into a night club, the night club's music should probably be 2D, while the individual voices of characters in the club should be mono with their realistic positioning being handled by Unity.

You should attach the Audio Listener to either the Main Camera or to the GameObject that represents the player. Try both to find what suits your game best.

Hints

Audio Source

The Audio Source plays back an Audio Clip in the scene. If the Audio Clip is a 3D clip, the source is played back at a given position and will attenuate over distance. The audio can be spread out between speakers (stereo to 7.1) (Spread) and morphed between 3D and 2D (PanLevel). This can be controlled over distance with falloff curves. Also, if the listener is within one or multiple Reverb Zones, reverberations is applied to the source. (PRO only) Individual filters can be applied to each audio source for an even richer audio experience. See Audio Effects for more details.


The Audio Source gizmo in the Scene View and its settings in the inspector.

Properties

Audio ClipReference to the sound clip file that will be played.
MuteIf enabled the sound will be playing but muted.
Bypass EffectsThis Is to quickly "by-pass" filter effects applied to the audio source. An easy way to turn all effects on/off.
Play On AwakeIf enabled, the sound will start playing the moment the scene launches. If disabled, you need to start it using the Play() command from scripting.
LoopEnable this to make the Audio Clip loop when it reaches the end.
PriorityDetermines the priority of this audio source among all the ones that coexist in the scene. (Priority: 0 = most important. 256 = least important. Default = 128.). Use 0 for music tracks to avoid it getting occasionally swapped out.
VolumeHow loud the sound is at a distance of one world unit (one meter) from the Audio Listener.
PitchAmount of change in pitch due to slowdown/speed up of the Audio Clip. Value 1 is normal playback speed.
3D Sound SettingsSettings that are applied to the audio source if the Audio Clip is a 3D Sound.
Pan LevelSets how much the 3d engine has an effect on the audio source.
SpreadSets the spread angle to 3d stereo or multichannel sound in speaker space.
Doppler LevelDetermines how much doppler effect will be applied to this audio source (if is set to 0, then no effect is applied).
Min DistanceWithin the MinDistance, the sound will stay at loudest possible. Outside MinDistance it will begin to attenuate. Increase the MinDistance of a sound to make it 'louder' in a 3d world, and decrease it to make it 'quieter' in a 3d world.
Max DistanceThe distance where the sound stops attenuating at. Beyond this point it will stay at the volume it would be at MaxDistance units from the listener and will not attenuate any more.
Rolloff ModeHow fast the sound fades. The higher the value, the closer the Listener has to be before hearing the sound.(This is determined by a Graph).
Logarithmic RolloffThe sound is loud when you are close to the audio source, but when you get away from the object it decreases significantly fast.
Linear RolloffThe further away from the audio source you go, the less you can hear it.
Custom RolloffThe sound from the audio source behaves accordingly to how you set the graph of roll offs.
2D Sound SettingsSettings that are applied to the audio source if the Audio clip is a 2D Sound.
Pan 2DSets how much the engine has an effect on the audio source.

Types of Rolloff

There are three Rolloff modes: Logarithmic, Linear and Custom Rolloff. The Custom Rolloff can be modified by modifying the volume distance curve as described below. If you try to modify the volume distance function when it is set to Logarithmic or Linear, the type will automatically change to Custom Rolloff.


Rolloff Modes that an audio source can have.

Distance Functions

There are several properties of the audio that can be modified as a function of the distance between the audio source and the audio listener.

Volume: Amplitude(0.0 - 1.0) over distance.
Pan: Left(-1.0) to Right(1.0) over distance.
Spread: Angle (degrees 0.0 - 360.0) over distance.
Low-Pass (only if LowPassFilter is attached to the AudioSource): Cutoff Frequency (22000.0-10.0) over distance.


Distance functions for Volume, Pan, Spread and Low-Pass audio filter. The current distance to the Audio Listener is marked in the graph.

To modify the distance functions, you can edit the curves directly. For more information, see the guide to Editing Curves.

Creating Audio Sources

Audio Sources don't do anything without an assigned Audio Clip. The Clip is the actual sound file that will be played back. The Source is like a controller for starting and stopping playback of that clip, and modifying other audio properties.

To create a new Audio Source:

  1. Import your audio files into your Unity Project. These are now Audio Clips.
  2. Go to GameObject->Create Empty from the menubar.
  3. With the new GameObject selected, select Component->Audio->Audio Source.
  4. Assign the Audio Clip property of the Audio Source Component in the Inspector.

Note: If you want to create an Audio Source just for one Audio Clip that you have in the Assets folder then you can just drag that clip to the scene view - a GameObject with an Audio Source component will be created automatically for it. Dragging a clip onto on existing GameObject will attach the clip along with a new Audio Source if there isn't one already there. If the object does already have an Audio Source then the newly dragged clip will replace the one that the source currently uses.

Platform specific details

iOS

On mobile platforms compressed audio is encoded as MP3 for speedier decompression. Beware that this compression can remove samples at the end of the clip and potentially break a "perfect-looping" clip. Make sure the clip is right on a specific MP3 sample boundary to avoid sample clipping - tools to perform this task are widely available. For performance reasons audio clips can be played back using the Apple hardware codec. To enable this, check the "Use Hardware" checkbox in the import settings. See the Audio Clip documentation for more details.

Android

On mobile platforms compressed audio is encoded as MP3 for speedier decompression. Beware that this compression can remove samples at the end of the clip and potentially break a "perfect-looping" clip. Make sure the clip is right on a specific MP3 sample boundary to avoid sample clipping - tools to perform this task are widely available.

Audio Clip

Audio Clips contain the audio data used by Audio Sources. Unity supports mono, stereo and multichannel audio assets (up to eight channels). The audio file formats that Unity can import are .aif, .wav, .mp3, and .ogg. Unity can also import tracker modules in the .xm, .mod, .it, and .s3m formats. The tracker module assets behave the same way as any other audio assets in Unity although no waveform preview is available in the asset import inspector.


The Audio Clip inspector

Properties

Audio FormatThe specific format that will be used for the sound at runtime.
NativeThis option offers higher quality at the expense of larger file size and is best for very short sound effects.
CompressedThe compression results in smaller files but with somewhat lower quality compared to native audio. This format is best for medium length sound effects and music.
3D SoundIf enabled, the sound will play back in 3D space. Both Mono and Stereo sounds can be played in 3D.
Force to monoIf enabled, the audio clip will be down-mixed to a single channel sound.
Load TypeThe method Unity uses to load audio assets at runtime.
Decompress on loadAudio files will be decompressed as soon as they are loaded. Use this option for smaller compressed sounds to avoid the performance overhead of decompressing on the fly. Be aware that decompressing sounds on load will use about ten times more memory than keeping them compressed, so don't use this option for large files.
Compressed in memoryKeep sounds compressed in memory and decompress while playing. This option has a slight performance overhead (especially for Ogg/Vorbis compressed files) so only use it for bigger files where decompression on load would use a prohibitive amount of memory. Note that, due to technical limitations, this option will silently switch to Stream From Disc (see below) for Ogg Vorbis assets on platforms that use FMOD audio.
Stream from discStream audio data directly from disc. The memory used by this option is typically a small fraction of the file size, so it is very useful for music or other very long tracks. For performance reasons, it is usually advisable to stream only one or two files from disc at a time but the number of streams that can comfortably be handled depends on the hardware.
CompressionAmount of Compression to be applied to a Compressed clip. Statistics about the file size can be seen under the slider. A good approach to tuning this value is to drag the slider to a place that leaves the playback "good enough" while keeping the file small enough for your distribution requirements.
Hardware Decoding(iOS only) On iOS devices, Apple's hardware decoder can be used resulting in lower CPU overhead during decompression. Check out platform specific details for more info.
Gapless looping(Android/iOS only) Use this when compressing a seamless looping audio source file (in a non-compressed PCM format) to ensure perfect continuity is preserved at the seam. Standard MPEG encoders introduce a short silence at the loop point, which will be audible as a brief "click" or "pop".

Importing Audio Assets

Unity supports both Compressed and Native Audio. Any type of file (except MP3/Ogg Vorbis) will be initially imported as Native. Compressed audio files must be decompressed by the CPU while the game is running, but have smaller file size. If Stream is checked the audio is decompressed on the fly, otherwise it is decompressed completely as soon as it loads. Native PCM formats (WAV, AIFF) have the benefit of giving higher fidelity without increasing the CPU overhead, but files in these formats are typically much larger than compressed files. Module files (.mod,.it,.s3m..xm) can deliver very high quality with an extremely low footprint.

As a general rule of thumb, Compressed audio (or modules) are best for long files like background music or dialog, while Native is better for short sound effects. You should tweak the amount of Compression using the compression slider. Start with high compression and gradually reduce the setting to the point where the loss of sound quality is perceptible. Then, increase it again slightly until the perceived loss of quality disappears.

Using 3D Audio

If an audio clip is marked as a 3D Sound then it will be played back so as to simulate its position in the game world's 3D space. 3D sounds emulate the distance and location of sounds by attenuating volume and panning across speakers. Both mono and multiple channel sounds can be positioned in 3D. For multiple channel audio, use the spread option on the Audio Source to spread and split out the discrete channels in speaker space. Unity offers a variety of options to control and fine-tune the audio behavior in 3D space - see the Audio Source component reference for further details.

Platform specific details

iOS

On mobile platforms compressed audio is encoded as MP3 to take advantage of hardware decompression.

To improve performance, audio clips can be played back using the Apple hardware codec. To enable this option, check the "Hardware Decoding" checkbox in the Audio Importer. Note that only one hardware audio stream can be decompressed at a time, including the background iPod audio.

If the hardware decoder is not available, the decompression will fall back on the software decoder (on iPhone 3GS or later, Apple's software decoder is used in preference to Unity's own decoder (FMOD)).

Android

On mobile platforms compressed audio is encoded as MP3 to take advantage of hardware decompression.

Page last updated: 2007-11-16



Game Interface Elements

Unity gives you a number of options for creating your game's graphic user interface (GUI). You can use GUI Text and GUI Texture objects in the scene, or generate the interface from scripts using UnityGUI.

The rest of this page contains a detailed guide for getting up and running with UnityGUI.

GUI Scripting Guide

Overview

UnityGUI allows you to create a wide variety of highly functional GUIs very quickly and easily. Rather than creating a GUI object, manually positioning it, and then writing a script that handles its functionality, you can do everything at once with just a few lines of code. The code produces GUI controls that are instantiated, positioned and handled with a single function call.

For example, the following code will create and handle a button with no additional work in the editor or elsewhere:-

// JavaScript
function OnGUI () {
	if (GUI.Button (Rect (10,10,150,100), "I am a button")) {
		print ("You clicked the button!");
	}
}


// C#
using UnityEngine;
using System.Collections;

public class GUITest : MonoBehaviour {

	void OnGUI () {
		if (GUI.Button (new Rect (10,10,150,100), "I am a button")) {
			print ("You clicked the button!");
		}
	}
}

This is the button created by the code above

Although this example is very simple, there are very powerful and complex techniques available for use in UnityGUI. GUI construction is a broad subject but the following sections should help you get up to speed as quickly as possible. This guide can be read straight through or used as reference material.

UnityGUI Basics

This section covers the fundamental concepts of UnityGUI, giving you an overview as well as a set of working examples you can paste into your own code. UnityGUI is very friendly to play with, so this is a good place to get started.

Controls

This section lists every available Control in UnityGUI, along with code samples and images showing the results.

Customization

It is important to be able to change the appearance of the GUI to match the look of your game. All controls in UnityGUI can be customized with GUIStyles and GUISkins, as explained in this section.

Layout Modes

UnityGUI offers two ways to arrange your GUIs: you can manually place each control on the screen, or you can use an automatic layout system which works in a similar way to HTML tables. Either system can be used as desired and the two can be freely mixed. This section explains the functional differences between the two systems, including examples.

Extending UnityGUI

UnityGUI is very easy to extend with new Control types. This chapter shows you how to make simple compound controls - complete with integration into Unity's event system.

Extending Unity Editor

The GUI of the Unity editor is actually written using UnityGUI. Consequently, the editor is highly extensible using the same type of code you would use for in-game GUI. In addition, there are a number of Editor-specific GUI controls to help you create custom editor GUI.

Page last updated: 2011-11-17



Networked Multiplayer

Realtime networking is a complex field but Unity makes it easy to add networking features to your game. Nevertheless, it is useful to have some idea of the scope of networking before using it in a game. This section explains the fundamentals of networking along with the specifics of Unity's implementation. If you have never created a network game before then it is strongly recommended that you work through this guide before getting started.

High Level Overview

This section outlines all the concepts involved in networking and serves as an introduction to deeper topics.

Networking Elements in Unity

This section of the guide covers Unity's implementation of the concepts explained in the overview.

RPC Details

Remote Procedure Call or RPC is a way of calling a function on a remote machine. This may be a client calling a function on the server, or the server calling a function on some or all clients. This section explains RPC concepts in detail.

State Synchronization

State Synchronization is a method of regularly updating a specific set of data across two or more game instances running on the network.

Minimizing Bandwidth

Every choice you make about where and how to share data will affect the network bandwidth your game uses. This page explains how bandwidth is used and how to keep usage to a minimum.

Network View

Network Views are Components you use to share data across the network and are a fundamental aspect of Unity networking. This page explains them in detail.

Network Instantiate

A complex subject in networking is ownership of an object and determination of who controls what. Network Instantiation handles this task for you, as explained in this section. Also covered are some more sophisticated alternatives for situations where you need more control over object ownership.

Master Server

The Master Server is like a game lobby where servers can advertise their presence to clients. It can also enable communication from behind a firewall or home network using a technique called NAT punchthrough (with help from a facilitator) to make sure your players can always connect with each other. This page explains how to use the Master Server.

Page last updated: 2011-11-17



iphone-GettingStarted

Building games for devices like the iPhone and iPad requires a different approach than you would use for desktop PC games. Unlike the PC market, your target hardware is standardized and not as fast or powerful as a computer with a dedicated video card. Because of this, you will have to approach the development of your games for these platforms a little differently. Also, the features available in Unity for iOS differ slightly from those for desktop PCs.

Setting Up Your Apple Developer Account

Before you can run Unity iOS games on the actual device, you will need to have your Apple Developer account approved and set up. This includes establishing your team, adding your devices, and finalizing your provisioning profiles. All this setup is performed through Apple's developer website. Since this is a complex process, we have provided a basic outline of the tasks that must be completed before you can run code on your iOS devices. However, the best thing to do is follow the step-by-step instructions at Apple's iPhone Developer portal.

Note: We recommend that you set up your Apple Developer account before proceeding because you will need it to use Unity to its full potential with iOS.

The Unity XCode Project

When you build the Unity iOS game an XCode project is generated. This project is required to sign, compile and prepare your game for distribution. See the Unity XCode project manual page for further information.

Accessing iOS Functionality

Unity provides a number of scripting APIs to access the multi-touch screen, accelerometer, device geographical location system and much more. You can find out more about the script classes on the iOS scripting page.

Exposing Native C, C++ or Objective-C Code to Scripts

Unity allows you to call custom native functions written in C, C++ or Objective-C directly from C# scripts. To find out how to bind native functions, visit the plugins page.

Prepare Your Application for In-App Purchases

The Unity iOS runtime allows you to download new content and you can use this feature to implement in-app purchases. See the downloadable content manual page for further information.

Occlusion Culling

Unity supports occlusion culling which is useful for squeezing high performance out of complex scenes with many objects. See the occlusion culling manual page for further information.

Splash Screen Customization

See the splash screen customization page to find out how to change the image your game shows while launching.

Troubleshooting and Reporting Crashes.

If you are experiencing crashes on the iOS device, please consult the iOS troubleshooting page for a list of common issues and solutions. If you can't find a solution here then please file a bug report for the crash (menu: Help > Report A Bug in the Unity editor).

How Unity's iOS and Desktop Targets Differ

Statically Typed JavaScript

Dynamic typing in JavaScript is always turned off in Unity when targetting iOS (this is equivalent to #pragma strict getting added to all your scripts automatically). Static typing greatly improves performance, which is especially important on iOS devices. When you switch an existing Unity project to the iOS target, you will get compiler errors if you are using dynamic typing. You can easily fix these either by using explicitly declared types for the variables that are causing errors or taking advantage of type inference.

MP3 Instead of Ogg Vorbis Audio Compression

For performance reasons, MP3 compression is favored on iOS devices. If your project contains audio files with Ogg Vorbis compression, they will be re-compressed to MP3 during the build. Consult the audio clip documentation for more information on using compressed audio on the iPhone.

PVRTC Instead of DXT Texture Compression

Unity iOS does not support DXT textures. Instead, PVRTC texture compression is natively supported by iPhone/iPad devices. Consult the texture import settings documentation to learn more about iOS texture formats.

Movie Playback

MovieTextures are not supported on iOS. Instead, full-screen streaming playback is provided via scripting functions. To learn about the supported file formats and scripting API, consult the movie page in the manual.

Further Reading

Page last updated: 2013-02-27



iphone-basic

This section covers the most common and important questions that come up when starting to work with iOS.

Prerequisites

I've just received iPhone Developer approval from Apple, but I've never developed for iOS before. What do I do first?

A: Download the SDK, get up and running on the Apple developer site, and set up your team, devices, and provisioning. We've provided a basic list of steps to get you started.

Can Unity-built games run in the iPhone Simulator?

A: No, but Unity iOS can build to iPad Simulator if you're using the latest SDK. However the simulator itself is not very useful for Unity because it does not simulate all inputs from iOS or properly emulate the performance you get on the iPhone/iPad. You should test out gameplay directly inside Unity using the iPhone/iPad as a remote control while it is running the Unity Remote application. Then, when you are ready to test performance and optimize the game, you publish to iOS devices.

Unity Features

How do I work with the touch screen and accelerometer?

A: In the scripting reference inside your Unity iOS installation, you will find classes that provide the hooks into the device's functionality that you will need to build your apps. Consult the Input page for more information.

My existing particle systems seem to run very slowly on iOS. What should I do?

A: iOS has relatively low fillrate. If your particles cover a rather large portion of the screen with multiple layers, it will kill iOS performance even with the simplest shader. We suggest baking your particle effects into a series of textures off-line. Then, at run-time, you can use 1-2 particles to display them via animated textures. You can get fairly decent looking effects with a minimum amount of overdraw this way.

Can I make a game that uses heavy physics?

A: Physics can be expensive on iOS as it requires a lot of floating point number crunching. You should completely avoid MeshColliders if at all possible, but they can be used if they are really necessary. To improve performance, use a low fixed framerate using Edit->Time->Fixed Delta Time. A framerate of 10-30 is recommended. Enable rigidbody interpolation to achieve smooth motion while using low physics frame rates. In order to achieve completely fluid framerate without oscillations, it is best to pick fixed deltaTime value based on the average framerate your game is getting on iOS. Either 1:1 or half the frame rate is recommended. For example, if you get 30 fps, you should use 15 or 30 fps for fixed frame rate (0.033 or 0.066)

Can I access the gallery, music library or the native iPod player in Unity iOS?

A: Yes - if you implement it. Unity iPhone supports the native plugin system, where you can add any feature you need -- including access to Gallery, Music library, iPod Player and any other feature that the iOS SDK exposes. Unity iOS does not provide an API for accessing the listed features through Unity scripts.

UnityGUI Considerations

What kind of performance impact will UnityGUI make on my games?

A: UnityGUI is fairly expensive when many controls are used. It is ideal to limit your use of UnityGUI to game menus or very minimal GUI Controls while your game is running. It is important to note that every object with a script containing an OnGUI() call will require additional processor time -- even if it is an empty OnGUI() block. It is best to disable any scripts that have an OnGUI() call if the GUI Controls are not being used. You can do this by marking the script as enabled = false.

Any other tips for using UnityGUI?

A: Try using GUILayout as little as possible. If you are not using GUILayout at all from one OnGUI() call, you can disable all GUILayout rendering using MonoBehaviour.useGUILayout = false; This doubles GUI rendering performance. Finally, use as few GUI elements while rendering 3D scenes as possible.

Page last updated: 2013-10-10



unity-remote

Unity Remote is an application that allows you to use your iOS device as a remote control for your project in Unity. This is useful during development since it is much quicker to test your project in the editor with remote control than to build and deploy it to the device after each change.

Where can I find Unity Remote?

Unity remote is available for download from the AppStore at no charge. If you prefer to build and deploy the application yourself, you can download the source here at the Unity website.

How do I build Unity Remote?

First, download the project source code here and unzip it to your preferred location. The zip file contains an XCode project to build Unity Remote and install it on your device.

Assuming you have already created the provisioning profile and successfully installed iOS builds on your device, you just need to open the Xcode project file UnityRemote.xcodeproj. Once XCode is launched, you should click "Build and Go" to install the app on your iOS device. If you have never built and run applications before, we recommend that you try building some of the Apple examples first to familiarize yourself with XCode and iOS.

Once Unity Remote is installed, make sure your device is connected via Wi-Fi to the same network as your development machine or else connected to the machine directly via USB. Launch Unity Remote on your iPhone/iPad while Unity is running on your computer and select your computer from the list that appears. Now, whenever you enter Play mode in the Editor, your device will act as a remote control that you can use for developing and testing your game. You can control the application with the device wirelessly and you will also see a low-res version of the app on the device's screen.

Note: The Unity iOS editor cannot emulate the device's hardware perfectly, so you may not get the exact behavior (graphics performance, touch responsiveness, sounds playback, etc) that you would on a real device.

Xcode shows strange errors while deploying Unity Remote to my device. What should I do?

This indicates that the default Identifier in the Unity Remote project is not compatible with your provisioning profile. You will have to alter this Identifier manually in your XCode project. The Identifier must match your provisioning profile.

You will need to create an AppID with an trailing asterisk if you have not already done so; you can do this in the Program Portal on Apple's iPhone Developer Program. First, go to the Program Portal and choose the AppIDs tab. Then, click the Add ID button in the top right corner and type your usual bundle identifier followed by dot and asterisk (eg, com.mycompany.*) in the App ID Bundle Seed ID and Bundle Identifier field. Add the new AppID to your provisioning profile, then download and reinstall it. Don't forget to restart Xcode afterwards. If you have any problems creating the AppID, consult the Provisioning How-to section on Apple's website.


Don't forget to change the Identifier before you install Unity Remote on your device.

Open the Unity Remote project with XCode. From the menu, select Project->Edit Active Target "Unity Remote". This will open a new window entitled Target "Unity Remote" Info. Select the Properties tab. Change the Identifier property field from com.unity3d.UnityRemote to the bundle identifier in your AppID followed by "." (dot) followed by "UnityRemote". For example, if your provisioning profile contains ##.com.mycompany.* AppID, then change the Identifier field to com.mycompany.UnityRemote.

Next, select Build->Clean all targets from the menu, and compile and install Unity Remote again. You may also need to change the active SDK from Simulator to Device - 2.0 | Release. There is no problem using SDK 2.0 even if your device runs a newer version of the OS.

I'm getting really poor graphics quality when running my game in Unity Remote. What can I do to improve it?

When you use Unity Remote, the game actually runs on your Mac while its visual content is heavily compressed and streamed to the device. As a result, what you see on the device screen is just a low-res version of what the app would really look like. You should check how the game runs on the device occasionally by building and deploying the app (select File->Build & Run in the Unity editor).

Unity Remote is laggy. Can I improve it?

The performance of Unity Remote depends heavily on the speed of the Wi-Fi network, the quality of the networking hardware and other factors. For the best experience, create an ad-hoc network between your Mac and iOS device. Click the Airport icon on your Mac and choose "Create Network". Then, enter a name and password and click OK. On the device, choose Settings->Wi-Fi and select the new Wi-Fi network you have just created. Remember that an ad-hoc network is really a wireless connection that does not involve a wireless access point. Therefore, you will usually not have internet access while using ad-hoc networking.

Turning Bluetooth off on both on your iPhone/iPad and on Mac should also improve connection quality.

If you do not need to see the game view on the device, you can turn image synchronization off in the Remote machine list. This will reduce the network traffic needed for the Remote to work.

The connection to Unity Remote is easily lost

This can be due to a problem with the installation or other factors that prevent Unity Remote from functioning properly. Try the following steps in sequence, checking if the performance improves at each step before moving on to the next:-

  1. First of all, check if Bluetooth is switched on. Both your Mac and iOS device should have Bluetooth disabled for best performance.
  2. Delete the settings file located at ~/Library/Preferences/com.unity3d.UnityEditoriPhone.plist
  3. Reinstall the game on your iPhone/iPad.
  4. Reinstall Unity on your Mac.
  5. As a last resort, performing a hard reset on the iOS device can sometimes improve the performance of Unity Remote.

If you still experience problems then try installing Unity Remote on another device (in another location if possible) and see if it gives you better results. There could be problems with RF interference or other software influencing the performance of the wireless adapter on your Mac or iOS device.

Unity Remote doesn't see my Mac. What should I do?

Page last updated: 2013-01-07



iphone-API

Most features of the iOS devices are exposed through the Input and Handheld classes. For cross-platform projects, UNITY_IPHONE is defined for conditionally compiling iOS-specific C# code.

Further Reading

Page last updated: 2012-11-23



iphone-Input

Desktop

Unity supports keyboard, joystick and gamepad input.

Virtual axes and buttons can be created in the Input Manager, and end users can configure Keyboard input in a nice screen configuration dialog.

You can setup joysticks, gamepads, keyboard, and mouse, then access them all through one simple scripting interface.

From scripts, all virtual axes are accessed by their name.

Every project has the following default input axes when it's created:

  • Horizontal and Vertical are mapped to w, a, s, d and the arrow keys.
  • Fire1, Fire2, Fire3 are mapped to Control, Option (Alt), and Command, respectively.
  • Mouse X and Mouse Y are mapped to the delta of mouse movement.
  • Window Shake X and Window Shake Y is mapped to the movement of the window.

Adding new Input Axes

If you want to add new virtual axes go to the Edit->Project Settings->Input menu. Here you can also change the settings of each axis.

You map each axis to two buttons on a joystick, mouse, or keyboard keys.

NameThe name of the string used to check this axis from a script.
Descriptive NamePositive value name displayed in the input tab of the Configuration dialog for standalone builds.
Descriptive Negative NameNegative value name displayed in the Input tab of the Configuration dialog for standalone builds.
Negative ButtonThe button used to push the axis in the negative direction.
Positive ButtonThe button used to push the axis in the positive direction.
Alt Negative ButtonAlternative button used to push the axis in the negative direction.
Alt Positive ButtonAlternative button used to push the axis in the positive direction.
GravitySpeed in units per second that the axis falls toward neutral when no buttons are pressed.
DeadSize of the analog dead zone. All analog device values within this range result map to neutral.
SensitivitySpeed in units per second that the the axis will move toward the target value. This is for digital devices only.
SnapIf enabled, the axis value will reset to zero when pressing a button of the opposite direction.
InvertIf enabled, the Negative Buttons provide a positive value, and vice-versa.
TypeThe type of inputs that will control this axis.
AxisThe axis of a connected device that will control this axis.
Joy NumThe connected Joystick that will control this axis.

Use these settings to fine tune the look and feel of input. They are all documented with tooltips in the Editor as well.

Using Input Axes from Scripts

You can query the current state from a script like this:

value = Input.GetAxis ("Horizontal");

An axis has a value between -1 and 1. The neutral position is 0. This is the case for joystick input and keyboard input.

However, Mouse Delta and Window Shake Delta are how much the mouse or window moved during the last frame. This means it can be larger than 1 or smaller than -1 when the user moves the mouse quickly.

It is possible to create multiple axes with the same name. When getting the input axis, the axis with the largest absolute value will be returned. This makes it possible to assign more than one input device to one axis name. For example, create one axis for keyboard input and one axis for joystick input with the same name. If the user is using the joystick, input will come from the joystick, otherwise input will come from the keyboard. This way you don't have to consider where the input comes from when writing scripts.

Button Names

To map a key to an axis, you have to enter the key's name in the Positive Button or Negative Button property in the Inspector.

The names of keys follow this convention:

  • Normal keys: "a", "b", "c" ...
  • Number keys: "1", "2", "3", ...
  • Arrow keys: "up", "down", "left", "right"
  • Keypad keys: "[1]", "[2]", "[3]", "[+]", "[equals]"
  • Modifier keys: "right shift", "left shift", "right ctrl", "left ctrl", "right alt", "left alt", "right cmd", "left cmd"
  • Mouse Buttons: "mouse 0", "mouse 1", "mouse 2", ...
  • Joystick Buttons (from any joystick): "joystick button 0", "joystick button 1", "joystick button 2", ...
  • Joystick Buttons (from a specific joystick): "joystick 1 button 0", "joystick 1 button 1", "joystick 2 button 0", ...
  • Special keys: "backspace", "tab", "return", "escape", "space", "delete", "enter", "insert", "home", "end", "page up", "page down"
  • Function keys: "f1", "f2", "f3", ...

The names used to identify the keys are the same in the scripting interface and the Inspector.

value = Input.GetKey ("a");

Mobile Input

On iOS and Android, the Input class offers access to touchscreen, accelerometer and geographical/location input.

Access to keyboard on mobile devices is provided via the iOS keyboard.

Multi-Touch Screen

The iPhone and iPod Touch devices are capable of tracking up to five fingers touching the screen simultaneously. You can retrieve the status of each finger touching the screen during the last frame by accessing the Input.touches property array.

Android devices don't have a unified limit on how many fingers they track. Instead, it varies from device to device and can be anything from two-touch on older devices to five fingers on some newer devices.

Each finger touch is represented by an Input.Touch data structure:

fingerIdThe unique index for a touch.
positionThe screen position of the touch.
deltaPositionThe screen position change since the last frame.
deltaTimeAmount of time that has passed since the last state change.
tapCountThe iPhone/iPad screen is able to distinguish quick finger taps by the user. This counter will let you know how many times the user has tapped the screen without moving a finger to the sides. Android devices do not count number of taps, this field is always 1.
phaseDescribes so called "phase" or the state of the touch. It can help you determine if the touch just began, if user moved the finger or if he just lifted the finger.

Phase can be one of the following:

BeganA finger just touched the screen.
MovedA finger moved on the screen.
StationaryA finger is touching the screen but hasn't moved since the last frame.
EndedA finger was lifted from the screen. This is the final phase of a touch.
CanceledThe system cancelled tracking for the touch, as when (for example) the user puts the device to her face or more than five touches happened simultaneously. This is the final phase of a touch.

Following is an example script which will shoot a ray whenever the user taps on the screen:

var particle : GameObject;
function Update () {
	for (var touch : Touch in Input.touches) {
		if (touch.phase == TouchPhase.Began) {
			// Construct a ray from the current touch coordinates
			var ray = Camera.main.ScreenPointToRay (touch.position);
			if (Physics.Raycast (ray)) {
				// Create a particle if hit
				Instantiate (particle, transform.position, transform.rotation);
			}
		}
	}
}

Mouse Simulation

On top of native touch support Unity iOS/Android provides a mouse simulation. You can use mouse functionality from the standard Input class.

Accelerometer

As the mobile device moves, a built-in accelerometer reports linear acceleration changes along the three primary axes in three-dimensional space. Acceleration along each axis is reported directly by the hardware as G-force values. A value of 1.0 represents a load of about +1g along a given axis while a value of -1.0 represents -1g. If you hold the device upright (with the home button at the bottom) in front of you, the X axis is positive along the right, the Y axis is positive directly up, and the Z axis is positive pointing toward you.

You can retrieve the accelerometer value by accessing the Input.acceleration property.

The following is an example script which will move an object using the accelerometer:

var speed = 10.0;
function Update () {
	var dir : Vector3 = Vector3.zero;

	// we assume that the device is held parallel to the ground
	// and the Home button is in the right hand

	// remap the device acceleration axis to game coordinates:
	//  1) XY plane of the device is mapped onto XZ plane
	//  2) rotated 90 degrees around Y axis
	dir.x = -Input.acceleration.y;
	dir.z = Input.acceleration.x;

	// clamp acceleration vector to the unit sphere
	if (dir.sqrMagnitude > 1)
		dir.Normalize();

	// Make it move 10 meters per second instead of 10 meters per frame...
	dir *= Time.deltaTime;

	// Move object
	transform.Translate (dir * speed);
}

Low-Pass Filter

Accelerometer readings can be jerky and noisy. Applying low-pass filtering on the signal allows you to smooth it and get rid of high frequency noise.

The following script shows you how to apply low-pass filtering to accelerometer readings:

var AccelerometerUpdateInterval : float = 1.0 / 60.0;
var LowPassKernelWidthInSeconds : float = 1.0;

private var LowPassFilterFactor : float = AccelerometerUpdateInterval / LowPassKernelWidthInSeconds; // tweakable
private var lowPassValue : Vector3 = Vector3.zero;
function Start () {
	lowPassValue = Input.acceleration;
}

function LowPassFilterAccelerometer() : Vector3 {
	lowPassValue = Mathf.Lerp(lowPassValue, Input.acceleration, LowPassFilterFactor);
	return lowPassValue;
}

The greater the value of LowPassKernelWidthInSeconds, the slower the filtered value will converge towards the current input sample (and vice versa).

I'd like as much precision as possible when reading the accelerometer. What should I do?

Reading the Input.acceleration variable does not equal sampling the hardware. Put simply, Unity samples the hardware at a frequency of 60Hz and stores the result into the variable. In reality, things are a little bit more complicated -- accelerometer sampling doesn't occur at consistent time intervals, if under significant CPU loads. As a result, the system might report 2 samples during one frame, then 1 sample during the next frame.

You can access all measurements executed by accelerometer during the frame. The following code will illustrate a simple average of all the accelerometer events that were collected within the last frame:

var period : float = 0.0;
var acc : Vector3 = Vector3.zero;
for (var evnt : iPhoneAccelerationEvent  in iPhoneInput.accelerationEvents) {
	acc += evnt.acceleration * evnt.deltaTime;
	period += evnt.deltaTime;
}
if (period > 0)
	acc *= 1.0/period;
return acc;

iOS Game Controller support

Starting with OS 7, a standardized Game Controller Input API is provided by Apple. Unity support for this API comes as part of the standard Unity Input API.

Detecting attached Game Controllers

Calling Input.GetJoystickNames will enumerate the names of all attached controllers. Names follow the pattern: "[$profile_type,$connection_type] joystick $number by $model". $profile_type might be either "basic" or "extended", $connection_type is either "wired" or "wireless". It could be used to detect the kind of connected controller. It is worth re-checking this list every few seconds to detect if controllers have been attached or detached. Here’s an example how of to do it in C#:

    private bool connected = false;
    IEnumerator CheckForControllers()
    {
        while(true)
        {
            var controllers = Input.GetJoystickNames();
            if (!connected && controllers.Length > 0)
            {
                connected = true;
                Debug.Log("Connected");
            }
            else if (connected && controllers.Length == 0)
            {
                connected = false;
                Debug.Log("Disconnected");
            }
            yield return new WaitForSeconds(1f);
        }
    }
    void Awake()
    {
        StartCoroutine(CheckForControllers());
    }

When controllers are detected you can either hide on-screen touch controls or amend them to supplement controller input. The next task is to check for Game Controller input.

Handling input

Actual input scheme is highly dependent on the type of game you are developing. But in any case it goes down to reading axes and button states. Let's take following 2D game stage as simple example:

The player controls the bean character, which can move right or left, jump and fire at the bad guys. By default, the Unity Input "Horizontal" axis is mapped to basic profile game controller dpad and the left analog stick on extended profile controllers. So the code used to move the character back and forth is pretty simple:

    float h = Input.GetAxis("Horizontal");
    if(h * rigidbody2D.velocity.x < maxSpeed)
        rigidbody2D.AddForce(Vector2.right * h * moveForce);

You can set up jump and fire actions in Unity's Input Manager. Access it from the Unity editor menu as follows: Edit > Project Settings > Input. Lets pick joystick button "A" for the "Jump" action and "X" for "Fire". Open the following actions in the Unity Input Manager and specify "joystick button 14" for "Jump" and "joystick button 15" for "Fire".

The code handling them looks like this:

    if(Input.GetButtonDown("Jump") && grounded)
    {    
        rigidbody2D.AddForce(new Vector2(0f, jumpForce));
    }
    if(Input.GetButtonDown("Fire"))
    {
        Rigidbody2D bulletInstance = Instantiate(rocket, transform.position, Quaternion.Euler(new Vector3(0,0,0))) as Rigidbody2D;
        bulletInstance.velocity = new Vector2(speed, 0);
    }

The following cheatsheet should help you map controller input in the Unity Input Manager:

NameKeyCodeAxis
Ajoystick button 14N/A
Bjoystick button 13N/A
Xjoystick button 15N/A
Yjoystick button 12N/A
Left StickN/AAxis 1 (X) - Horizontal, Axis 2 (Y) - Vertical
Right StickN/AAxis 3 - Horizontal, Axis 4 - Vertical
Dpadjoystick button 4 .. joystick button 7Basic profile only: Axis 1 (X) - Horizontal, Axis 2 (Y) - Vertical
Pausejoystick button 0N/A
L1/R1joystick button 8/joystick button 9N/A
L2/R2joystick button 10/joystick button 11N/A

Final notes on Game Controller API support

The Game Controller framework is loaded dynamically by Unity iOS runtime only if it is available. For older iOS versions it will just return an empty list of controllers.

Apple documentation explicitly states that controller input must be optional and your game should be playable without them.

Page last updated: 2013-11-26



iOS-Keyboard

In most cases, Unity will handle keyboard input automatically for GUI elements but it is also easy to show the keyboard on demand from a script.

iOS

Using the Keyboard

GUI Elements

The keyboard will appear automatically when a user taps on editable GUI elements. Currently, GUI.TextField, GUI.TextArea and GUI.PasswordField will display the keyboard; see the GUI class documentation for further details.

Manual Keyboard Handling

Use the TouchScreenKeyboard.Open() function to open the keyboard. Please see the TouchScreenKeyboard scripting reference for the parameters that this function takes.

Keyboard Type Summary

The Keyboard supports the following types:

TouchScreenKeyboardType.DefaultLetters. Can be switched to keyboard with numbers and punctuation.
TouchScreenKeyboardType.ASCIICapableLetters. Can be switched to keyboard with numbers and punctuation.
TouchScreenKeyboardType.NumbersAndPunctuationNumbers and punctuation. Can be switched to keyboard with letters.
TouchScreenKeyboardType.URLLetters with slash and .com buttons. Can be switched to keyboard with numbers and punctuation.
TouchScreenKeyboardType.NumberPadOnly numbers from 0 to 9.
TouchScreenKeyboardType.PhonePadKeyboard used to enter phone numbers.
TouchScreenKeyboardType.NamePhonePadLetters. Can be switched to phone keyboard.
TouchScreenKeyboardType.EmailAddressLetters with @ sign. Can be switched to keyboard with numbers and punctuation.

Text Preview

By default, an edit box will be created and placed on top of the keyboard after it appears. This works as preview of the text that user is typing, so the text is always visible for the user. However, you can disable text preview by setting TouchScreenKeyboard.hideInput to true. Note that this works only for certain keyboard types and input modes. For example, it will not work for phone keypads and multi-line text input. In such cases, the edit box will always appear. TouchScreenKeyboard.hideInput is a global variable and will affect all keyboards.

Visibility and Keyboard Size

There are three keyboard properties in TouchScreenKeyboard that determine keyboard visibility status and size on the screen.

visibleReturns true if the keyboard is fully visible on the screen and can be used to enter characters.
areaReturns the position and dimensions of the keyboard.
activeReturns true if the keyboard is activated. This property is not static property. You must have a keyboard instance to use this property.

Note that TouchScreenKeyboard.area will return a Rect with position and size set to 0 until the keyboard is fully visible on the screen. You should not query this value immediately after TouchScreenKeyboard.Open(). The sequence of keyboard events is as follows:

  • TouchScreenKeyboard.Open() is called. TouchScreenKeyboard.active returns true. TouchScreenKeyboard.visible returns false. TouchScreenKeyboard.area returns (0, 0, 0, 0).
  • Keyboard slides out into the screen. All properties remain the same.
  • Keyboard stops sliding. TouchScreenKeyboard.active returns true. TouchScreenKeyboard.visible returns true. TouchScreenKeyboard.area returns real position and size of the keyboard.

Secure Text Input

It is possible to configure the keyboard to hide symbols when typing. This is useful when users are required to enter sensitive information (such as passwords). To manually open keyboard with secure text input enabled, use the following code:

TouchScreenKeyboard.Open("", TouchScreenKeyboardType.Default, false, false, true);

Hiding text while typing

Alert keyboard

To display the keyboard with a black semi-transparent background instead of the classic opaque, call TouchScreenKeyboard.Open() as follows:

TouchScreenKeyboard.Open("", TouchScreenKeyboardType.Default, false, false, true, true);

Classic keyboard

Alert keyboard

Android

Unity Android reuses the iOS API to display system keyboard. Even though Unity Android supports most of the functionality of its iPhone counterpart, there are two aspects which are not supported:

  • TouchScreenKeyboard.hideInput
  • TouchScreenKeyboard.area

Please also note that the layout of a TouchScreenKeyboardType can differ somewhat between devices.

Page last updated: 2013-04-23



iOS-Advanced

Device Properties

There are a number of device-specific properties that you can access. See the script reference pages for SystemInfo.deviceUniqueIdentifier, SystemInfo.deviceName, SystemInfo.deviceModel and SystemInfo.operatingSystem.

Anti-Piracy Check

Pirates will often hack an application (by removing AppStore DRM protection) and then redistribute it for free. Unity comes with an anti-piracy check which allows you to determine if your application was altered after it was submitted to the AppStore.

You can check if your application is genuine (not-hacked) with the Application.genuine property. If this property returns false then you might notify user that he is using a hacked application or maybe disable access to some functions of your application.

Note: Application.genuineCheckAvailable should be used along with Application.genuine to verify that application integrity can actually be confirmed. Accessing the Application.genuine property is a fairly expensive operation and so you shouldn't do it during frame updates or other time-critical code.

Vibration Support

You can trigger a vibration by calling Handheld.Vibrate. However, devices lacking vibration hardware will just ignore this call.

Activity Indicator

Mobile OSs have built-in activity indicators, that you can use during slow operations. Please check Handheld.StartActivityIndicator docs for usage sample.

Screen Orientation

Unity iOS/Android allows you to control current screen orientation. Detecting a change in orientation or forcing some specific orientation can be useful if you want to create game behaviors depending on how the user is holding the device.

You can retrieve device orientation by accessing the Screen.orientation property. Orientation can be one of the following:

PortraitThe device is in portrait mode, with the device held upright and the home button at the bottom.
PortraitUpsideDownThe device is in portrait mode but upside down, with the device held upright and the home button at the top.
LandscapeLeftThe device is in landscape mode, with the device held upright and the home button on the right side.
LandscapeRightThe device is in landscape mode, with the device held upright and the home button on the left side.

You can control screen orientation by setting Screen.orientation to one of those, or to ScreenOrientation.AutoRotation. When you want auto-rotation, you can disable some orientation on a case by case basis. See the script reference pages for Screen.autorotateToPortrait, Screen.autorotateToPortraitUpsideDown, Screen.autorotateToLandscapeLeft andScreen.autorotateToLandscapeRight

iOS

Advanced iOS scripting

Determining Device Generation

Different device generations support different functionality and have widely varying performance. You should query the device's generation and decide which functionality should be disabled to compensate for slower devices. You can find the device generation from the iPhone.generation property.

More information about different device generations, performance and supported functionality can be found in our iPhone Hardware Guide.

Android

Advanced Android scripting

Determining Device Generation

Different Android devices support different functionality and have widely varying performance. You should target specific devices or device families and decide which functionality should be disabled to compensate for slower devices. There are a number of device specific properties that you can access to which device is being used.

Note: Android Marketplace does some additional compatibility filtering, so you should not be concerned if an ARMv7-only app optimised for OGLES2 is offered to some old slow devices.

Page last updated: 2013-09-12



iOS-DotNet

iOS

Now Unity iOS supports two .NET API compatibility levels: .NET 2.0 and a subset of .NET 2.0 .You can select the appropriate level in the Player Settings.

.NET API 2.0

Unity supports the .NET 2.0 API profile. This is close to the full .NET 2.0 API and offers the best compatibility with pre-existing .NET code. However, the application's build size and startup time will be relatively poor.

Note: Unity iOS does not support namespaces in scripts. If you have a third party library supplied as source code then the best approach is to compile it to a DLL outside Unity and then drop the DLL file into your project's Assets folder.

.NET 2.0 Subset

Unity also supports the .NET 2.0 Subset API profile. This is close to the Mono "monotouch" profile, so many limitations of the "monotouch" profile also apply to Unity's .NET 2.0 Subset profile. More information on the limitations of the "monotouch" profile can be found here. The advantage of using this profile is reduced build size (and startup time) but this comes at the expense of compatibility with existing .NET code.

Android

Unity Android supports two .NET API compatibility levels: .NET 2.0 and a subset of .NET 2.0 You can select the appropriate level in the Player Settings.

.NET API 2.0

Unity supports the .NET 2.0 API profile; It is close to the full .NET 2.0 API and offers the best compatibility with pre-existing .NET code. However, the application's build size and startup time will be relatively poor.

Note: Unity Android does not support namespaces in scripts. If you have a third party library supplied as source code then the best approach is to compile it to a DLL outside Unity and then drop the DLL file into your project's Assets folder.

.NET 2.0 Subset

Unity also supports the .NET 2.0 Subset API profile. This is close to the Mono "monotouch" profile, so many limitations of the "monotouch" profile also apply to Unity's .NET 2.0 Subset profile. More information on the limitations of the "monotouch" profile can be found here. The advantage of using this profile is reduced build size (and startup time) but this comes at the expense of compatibility with existing .NET code.

Page last updated: 2013-08-12



iphone-Hardware

Hardware models

The following list summarizes iOS hardware available in devices of various generations:

iPhone Models

Original iPhone

iPhone 3G


iPhone 3G: Fixed-function graphics (no fancy shaders), very slow CPU and GPU.

iPhone 3GS

   
   

iPhone 3GS: Shader-capable hardware, per-pixel-lighting (bumpmaps) can only be on small portions of the screen at once.

Requires scripting optimization for complex games. This is the average hardware of the app market as of July 2012

iPhone 4

    
    

iPhone 4S

    
    

The iPhone 4S, with the new A5 chip, is capable of rendering complex shaders throughout the entire screen. Even image effects may be possible. However, optimizing your shaders is still crucial. But if your game isn't trying to push limits of the device, optimizing scripting and gameplay is probably as much of a waste of time on this generation of devices as it is on PC.

iPhone 5

    
    

iPod Touch Models

iPod Touch 1st generation


iPod Touch: Fixed-function graphics (no fancy shaders), very slow CPU and GPU.

iPod Touch 2nd generation

iPod Touch 3rd generation


iPod Touch 3rd gen: Shader-capable hardware, per-pixel-lighting (bumpmaps) can only be on small portions of the screen at once.

Requires scripting optimization for complex games. This is the average hardware of the app market as of July 2012

iPod Touch 4th generation

iPod Touch 5th generation

iPad Models

iPad

    
    

iPad: Similar to iPod Touch 4th Generation and iPhone 4.

iPad 2

    
    

iPad2: The A5 can do full screen bumpmapping, assuming the shader is simple enough. However, it is likely that your game will perform best with bumpmapping only on crucial objects. Full screen image effects still out of reach. Scripting optimization less important.

iPad (3rd generation)

    
    

The iPad 3 has been shown to be capable of render-to-texture effects such as reflective water and fullscreen image effects. However, optimized shaders are still crucial. But if your game isn't trying to push limits of the device, optimizing scripting and gameplay is probably as much of a waste of time on this generation of devices as it is on PC.

iPad (4rd generation)

    
    

Graphics Processing Unit and Hidden Surface Removal

The iPhone/iPad graphics processing unit (GPU) is a Tile-Based Deferred Renderer. In contrast with most GPUs in desktop computers, the iPhone/iPad GPU focuses on minimizing the work required to render an image as early as possible in the processing of a scene. That way, only the visible pixels will consume processing resources.

The GPU's frame buffer is divided up into tiles and rendering happens tile by tile. First, triangles for the whole frame are gathered and assigned to the tiles. Then, visible fragments of each triangle are chosen. Finally, the selected triangle fragments are passed to the rasterizer (triangle fragments occluded from the camera are rejected at this stage).

In other words, the iPhone/iPad GPU implements a Hidden Surface Removal operation at reduced cost. Such an architecture consumes less memory bandwidth, has lower power consumption and utilizes the texture cache better. Tile-Based Deferred Rendering allows the device to reject occluded fragments before actual rasterization, which helps to keep overdraw low.

For more information see also:-

MBX series

Older devices such as the original iPhone, iPhone 3G and iPod Touch 1st and 2nd Generation are equipped with the MBX series of GPUs. The MBX series supports only OpenGL ES1.1, the fixed function Transform/Lighting pipeline and two textures per fragment.

SGX series

Starting with the iPhone 3GS, newer devices are equipped with the SGX series of GPUs. The SGX series features support for the OpenGL ES2.0 rendering API and vertex and pixel shaders. The Fixed-function pipeline is not supported natively on such GPUs, but instead is emulated by generating vertex and pixel shaders with analogous functionality on the fly.

The SGX series fully supports MultiSample anti-aliasing.

Texture Compression

The only texture compression format supported by iOS is PVRTC. PVRTC provides support for RGB and RGBA (color information plus an alpha channel) texture formats and can compress a single pixel to two or four bits.

The PVRTC format is essential to reduce the memory footprint and to reduce consumption of memory bandwidth (ie, the rate at which data can be read from memory, which is usually very limited on mobile devices).

Vertex Processing Unit

The iPhone/iPad has a dedicated unit responsible for vertex processing which runs calculations in parallel with rasterization. In order to achieve better parallelization, the iPhone/iPad processes vertices one frame ahead of the rasterizer.

Unified Memory Architecture

Both the CPU and GPU on the iPhone/iPad share the same memory. The advantage is that you don't need to worry about running out of video memory for your textures (unless, of course, you run out of main memory too). The disadvantage is that you share the same memory bandwidth for gameplay and graphics. The more memory bandwidth you dedicate to graphics, the less you will have for gameplay and physics.

Multimedia CoProcessing Unit

The iPhone/iPad main CPU is equipped with a powerful SIMD (Single Instruction, Multiple Data) coprocessor supporting either the VFP or the NEON architecture. The Unity iOS run-time takes advantage of these units for multiple tasks such as calculating skinned mesh transformations, geometry batching, audio processing and other calculation-intensive operations.

Page last updated: 2013-07-18



iphone-performance

This section covers optimzations which are unique to iOS devices. For more information on optimizing for mobile devices, see the Practical Guide to Optimization for Mobiles.

Page last updated: 2012-07-30



iphone-iOS-Optimization

This page details optimizations which are unique to iOS deployment. For more information on optimizing for mobile devices, see the Practical Guide to Optimization for Mobiles.

Script Call Optimization

Most of the functions in the UnityEngine namespace are implemented in C/C++. Calling a C/C++ function from a Mono script involves a performance overhead. You can use iOS Script Call optimization (menu: Edit->Project Settings->Player) to save about 1 to 4 milliseconds per frame. The options for this setting are:-

Setting the Desired Framerate

Unity iOS allows you to change the frequency with which your application will try to execute its rendering loop, which is set to 30 frames per second by default. You can lower this number to save battery power but of course this saving will come at the expense of frame updates. Conversely, you can increase the framerate to give the rendering priority over other activities such as touch input and accelerometer processing. You will need to experiment with your choice of framerate to determine how it affects gameplay in your case.

If your application involves heavy computation or rendering and can maintain only 15 frames per second, say, then setting the desired frame rate higher than fifteen wouldn't give any extra performance. The application has to be optimized sufficiently to allow for a higher framerate.

To set the desired framerate, change Application.targetFrameRate.

Tuning Accelerometer Processing Frequency

If accelerometer input is processed too frequently then the overall performance of your game may suffer as a result. By default, a Unity iOS application will sample the accelerometer 60 times per second. You may see some performance benefit by reducing the accelerometer sampling frequency and it can even be set to zero for games that don't use accelerometer input. You can change the accelerometer frequency from the Other Settings panel in the iOS Player Settings.

Page last updated: 2013-08-12



iphone-InternalProfiler

Unity iOS and Android contain a built in profiler. This is included in all versions of the add-ons, and is not a Pro feature. (Pro add-ons do contain a more advanced profiler, however.) The built-in profiler emits console messages from the game running on device. These messages are written every 30 seconds and will provide insight into how the game is running. Understanding what these messages mean is not always easy, but as a minimum, you should quickly be able to determine if your game is CPU or GPU bound, and if CPU bound whether it's script code, or perhaps Mono garbage collection that is slowing you down. See later in this page to learn how to configure the built-in profiler.

What the Profiler Tells You

Here's an example of the built-in profiler's output.

iPhone/iPad Unity internal profiler stats:
cpu-player>    min:  9.8   max: 24.0   avg: 16.3
cpu-ogles-drv> min:  1.8   max:  8.2   avg:  4.3
cpu-waits-gpu> min:  0.8   max:  1.2   avg:  0.9
cpu-present>   min:  1.2   max:  3.9   avg:  1.6
frametime>     min: 31.9   max: 37.8   avg: 34.1
draw-call #>   min:   4    max:   9    avg:   6     | batched:    10
tris #>        min:  3590  max:  4561  avg:  3871   | batched:  3572
verts #>       min:  1940  max:  2487  avg:  2104   | batched:  1900
player-detail> physx:  1.2 animation:  1.2 culling:  0.5 skinning:  0.0 batching:  0.2 render: 12.0 fixed-update-count: 1 .. 2
mono-scripts>  update:  0.5   fixedUpdate:  0.0 coroutines:  0.0 
mono-memory>   used heap: 233472 allocated heap: 548864  max number of collections: 1 collection total duration:  5.7

All times are measured in milliseconds per frame. You can see the minimum, maximum and average times over the last thirty frames.

General CPU Activity

cpu-playerDisplays the time your game spends executing code inside the Unity engine and executing scripts on the CPU.
cpu-ogles-drvDisplays the time spent executing OpenGL ES driver code on the CPU. Many factors like the number of draw calls, number of internal rendering state changes, the rendering pipeline setup and even the number of processed vertices can have an effect on the driver stats.
cpu-waits-gpuDisplays the time the CPU is idle while waiting for the GPU to finish rendering. If this number exceeds 2-3 milliseconds then your application is most probably fillrate/GPU processing bound. If this value is too small then the profile skips displaying the value.
msaa-resolveThe time taken to apply anti-aliasiing.
cpu-presentThe amount of time spent executing the presentRenderbuffer command in OpenGL ES.
frametimeRepresents the overall time of a game frame. Note that iOS hardware is always locked at a 60Hz refresh rate, so you will always get multiples times of ~16.7ms (1000ms/60Hz = ~16.7ms).

Rendering Statistics

draw-call #The number of draw calls per frame. Keep it as low as possible.
tris #Total number of triangles sent for rendering.
verts #Total number of vertices sent for rendering. You should keep this number below 10000 if you use only static geometry but if you have lots of skinned geometry then you should keep it much lower.
batchedNumber of draw-calls, triangles and vertices which were automatically batched by the engine. Comparing these numbers with draw-call and triangle totals will give you an idea how well is your scene prepared for batching. Share as many materials as possible among your objects to improve batching.

Detailed Unity Player Statistics

The player-detail section provides a detailed breakdown of what is happening inside the engine:-

physxTime spent on physics.
animationTime spent animating bones.
cullingTime spent culling objects outside the camera frustum.
skinningTime spent applying animations to skinned meshes.
batchingTime spent batching geometry. Batching dynamic geometry is considerably more expensive than batching static geometry.
renderTime spent rendering visible objects.
fixed-update-countMinimum and maximum number of FixedUpdates executed during this frame. Too many FixedUpdates will deteriorate performance considerably.

Detailed Scripts Statistics

The mono-scripts section provides a detailed breakdown of the time spent executing code in the Mono runtime:

updateTotal time spent executing all Update() functions in scripts.
fixedUpdateTotal time spent executing all FixedUpdate() functions in scripts.
coroutinesTime spent inside script coroutines.

Detailed Statistics on Memory Allocated by Scripts

The mono-memory section gives you an idea of how memory is being managed by the Mono garbage collector:

allocated heapTotal amount of memory available for allocations. A garbage collection will be triggered if there is not enough memory left in the heap for a given allocation. If there is still not enough free memory even after the collection then the allocated heap will grow in size.
used heapThe portion of the allocated heap which is currently used up by objects. Every time you create a new class instance (not a struct) this number will grow until the next garbage collection.
max number of collectionsNumber of garbage collection passes during the last 30 frames.
collection total durationTotal time (in milliseconds) of all garbage collection passes that have happened during the last 30 frames.

Configuration

iOS

On iOS, it's disabled by default so to enable it, you need to open the Unity-generated XCode project, select the iPhone_Profiler.h file and change the line

#define ENABLE_INTERNAL_PROFILER 0

to

#define ENABLE_INTERNAL_PROFILER 1

Select View > Debug Area > Activate Console in the XCode menu to display the output console (GDB) and then run your project. Unity will output statistics to the console window every thirty frames.

Android

On Android, it is enabled by default. Just make sure Development Build is checked in the player settings when building, and the statistics should show up in logcat when run on the device. To view logcat, you need adb or the Android Debug Bridge. Once you have that, simply run the shell command adb logcat.

Page last updated: 2013-10-10



iphone-playerSizeOptimization

The two main ways of reducing the size of the player are by making proper Release build within Xcode and by changing the Stripping Level within Unity.

Building for distribution

Since Unity 4.2 it is expected that final release builds are made using Xcode 4.x/5.x command Product -> Archive. Using this command ensures that build is made with release configuration and all the debug symbols are stripped. After issuing this command latest Xcode switches to Organizer window Archives tab (you can navigate there manually via Window -> Organizer menu). You will find there two very useful functions there: App Store size estimation and Distribution. Build size estimation function works pretty well, but it is always recommended to have some small extra margin for error when aiming for 3G download limit (which currently is 50MB).

Note: xcodebuild utility currently does not have proper equivalent of "Archive" command. If you rely on building for distribution on this tool you might consider passing -Wl,-S,-x extra linker flag to it.

iOS Stripping Level (Advanced License feature)

The size optimizations activated by stripping work in the following way:

  1. Strip assemblies level: the scripts' bytecode is analyzed so that classes and methods that are not referenced from the scripts can be removed from the DLLs and thereby excluded from the AOT compilation phase. This optimization reduces the size of the main binary and accompanying DLLs and is safe as long as no reflection is used.
  2. Strip ByteCode level: any .NET DLLs (stored in the Data folder) are stripped down to metadata only. This is possible because all the code is already precompiled during the AOT phase and linked into the main binary.
  3. Use micro mscorlib level: a special, smaller version of mscorlib is used. Some components are removed from this library, for example, Security, Reflection.Emit, Remoting, non Gregorian calendars, etc. Also, interdependencies between internal components are minimized. This optimization reduces the main binary and mscorlib.dll size but it is not compatible with some System and System.Xml assembly classes, so use it with care.

These levels are cumulative, so level 3 optimization implicitly includes levels 2 and 1, while level 2 optimization includes level 1.

Note that Micro mscorlib is a heavily stripped-down version of the core library. Only those items that are required by the Mono runtime in Unity remain. Best practice for using micro mscorlib is not to use any classes or other features of .NET that are not required by your application. GUIDs are a good example of something you could omit; they can easily be replaced with custom made pseudo GUIDs and doing this would result in better performance and app size.

Tips

How to Deal with Stripping when Using Reflection

Stripping depends highly on static code analysis and sometimes this can't be done effectively, especially when dynamic features like reflection are used. In such cases, it is necessary to give some hints as to which classes shouldn't be touched. Unity supports a per-project custom stripping blacklist. Using the blacklist is a simple matter of creating a link.xml file and placing it into the Assets folder. An example of the contents of the link.xml file follows. Classes marked for preservation will not be affected by stripping:-

<linker>
       <assembly fullname="System.Web.Services">
               <type fullname="System.Web.Services.Protocols.SoapTypeStubInfo" preserve="all"/>
               <type fullname="System.Web.Services.Configuration.WebServicesConfigurationSectionHandler" preserve="all"/>
       </assembly>

       <assembly fullname="System">
               <type fullname="System.Net.Configuration.WebRequestModuleHandler" preserve="all"/>
               <type fullname="System.Net.HttpRequestCreator" preserve="all"/>
               <type fullname="System.Net.FileWebRequestCreator" preserve="all"/>
       </assembly>
</linker>

Note: it can sometimes be difficult to determine which classes are getting stripped in error even though the application requires them. You can often get useful information about this by running the stripped application on the simulator and checking the Xcode console for error messages.

Simple Checklist for Making Your Distribution as Small as Possible

  1. Minimize your assets: enable PVRTC compression for textures and reduce their resolution as far as possible. Also, minimize the number of uncompressed sounds. There are some additional tips for file size reduction here.
  2. Set the iOS Stripping Level to Use micro mscorlib.
  3. Set the script call optimization level to Fast but no exceptions.
  4. Don't use anything that lives in System.dll or System.Xml.dll in your code. These libraries are not compatible with micro mscorlib.
  5. Remove unnecessary code dependencies.
  6. Set the API Compatibility Level to .Net 2.0 subset. Note that .Net 2.0 subset has limited compatibility with other libraries.
  7. Don't use JS Arrays.
  8. Avoid generic containers in combination with value types, including structs.

How small can an app be made with Unity?

An empty project would take less than 22 MB in the App Store if all the size optimizations were turned off. If you own an Advanced License (and therefore have access to the stripping option), the empty scene with just the main camera can be reduced to less than 12 MB in the App Store (zipped and DRM attached).

Why did my app increase in size after being released to the App Store?

When publishing your app, Apple App Store service first encrypts the binary file and then compresses it via zip. Encryption increases ''randomness' of the code segment and thus makes it worse for compression. Check "Building for distribution" chapter above how to estimate App Store size before submission.

Page last updated: 2013-08-27



iphone-accountsetup

There are some steps you must follow before you can build and run any code (including Unity-built games) on your iOs device. These steps are prerequisite to publishing your own iOS games.

1. Apply to Apple to Become a Registered iPhone/iPad Developer

You do this through Apple's website: http://developer.apple.com/iphone/program/

2. Upgrade your Operating System and iTunes Installation

Please note that these are Apple's requirements as part of using the iPhone SDK, but the requirements can change from time to time.

3. Download the iPhone SDK

Download the latest iOS SDK from the iOS dev center and install it. Do not download the beta version of the SDK - you should use only the latest shipping version. Note that downloading and installing the iPhone SDK will also install XCode.

4. Get Your Device Identifier

Connect your iOS device to the Mac with the USB cable and launch XCode. XCode will detect your phone as a new device and you should register it with the "Use For Development" button. This will usually open the Organizer window but if it doesn't then go to Window->Organizer. You should see your iOS device) in the devices list on the left; select it and note your device's identifier code (which is about 40 characters long).

5. Add Your Device

Log in to the iPhone developer center and enter the program portal (button on the right). Go to the Devices page via the link on left side and then click the Add Device button on the right. Enter a name for your device (alphanumeric characters only) and your device's identifier code (noted in step 5 above). Click the Submit button when done.

6. Create a Certificate

From the iPhone Developer Program Portal, click the Certificates link on the left side and follow the instructions listed under How-To...

7. Download and Install the WWDR Intermediate Certificate

The download link is in the same "Certificates" section (just above the "Important Notice" rubric) as WWDR Intermediate Certificate. Once downloaded, double-click the certificate file to install it.

8. Create a Provisioning File

Provisioning profiles are a bit complex, and need to be set up according to the way you have organized your team. It is difficult to give general instructions for provisioning, so we recommend that you look at the Provisioning How-to section on the Apple Developer website.

Page last updated: 2011-11-08



iphone-unsupported

Graphics

Audio

Scripting

Features Restricted to Unity iOS Advanced License

Note: it is recommended to minimize your references to external libraries, because 1 MB of .NET CIL code roughly translates to 3-4 MB of ARM code. For example, if your application references System.dll and System.Xml.dll then it means additional 6 MB of ARM code if stripping is not used. At some point application will reach limit when linker will have troubles linking the code. If you care a lot about application size you might find C# a more suitable language for your code as is has less dependencies than JavaScript.

Page last updated: 2013-01-31



iphone-Plugins

This page describes Native Code Plugins for the iOS platform.

Building an Application with a Native Plugin for iOS

  1. Define your extern method in the C# file as follows:
    [DllImport ("__Internal")]
    private static extern float FooPluginFunction ();
  2. Set the editor to the iOS build target
  3. Add your native code source files to the generated XCode project's "Classes" folder (this folder is not overwritten when the project is updated, but don't forget to backup your native code).

If you are using C++ (.cpp) or Objective-C++ (.mm) to implement the plugin you must ensure the functions are declared with C linkage to avoid name mangling issues.

extern "C" {
  float FooPluginFunction ();
} 

Plugins written in C or Objective-C do not need this since these languages do not use name-mangling.

Using Your Plugin from C#

iOS native plugins can be called only when deployed on the actual device, so it is recommended to wrap all native code methods with an additional C# code layer. This code should check Application.platform and call native methods only when the app is running on the device; dummy values can be returned when the app runs in the Editor. See the Bonjour browser sample application for an example.

Calling C# / JavaScript back from native code

Unity iOS supports limited native-to-managed callback functionality via UnitySendMessage:
UnitySendMessage("GameObjectName1", "MethodName1", "Message to send");

This function has three parameters : the name of the target GameObject, the script method to call on that object and the message string to pass to the called method.

Known limitations:

  1. Only script methods that correspond to the following signature can be called from native code: function MethodName(message:string)
  2. Calls to UnitySendMessage are asynchronous and have a delay of one frame.

Automated plugin integration

Unity iOS supports automated plugin integration in a limited way. All files with extensions .a,.m,.mm,.c,.cpp located in the Assets/Plugins/iOS folder will be merged into the generated Xcode project automatically. However, merging is done by symlinking files from Assets/Plugins/iOS to the final destination, which might affect some workflows. The .h files are not included in the Xcode project tree, but they appear on the destination file system, thus allowing compilation of .m/.mm/.c/.cpp files.

Note: subfolders are currently not supported.

iOS Tips

  1. Managed-to-unmanaged calls are quite processor intensive on iOS. Try to avoid calling multiple native methods per frame.
  2. As mentioned above, wrap your native methods with an additional C# layer that calls native code on the device and returns dummy values in the Editor.
  3. String values returned from a native method should be UTF-8 encoded and allocated on the heap. Mono marshaling calls are free for strings like this.
  4. As mentioned above, the XCode project's "Classes" folder is a good place to store your native code because it is not overwritten when the project is updated.
  5. Another good place for storing native code is the Assets folder or one of its subfolders. Just add references from the XCode project to the native code files: right click on the "Classes" subfolder and choose "Add->Existing files...".

Examples

Bonjour Browser Sample

A simple example of the use of a native code plugin can be found here

This sample demonstrates how objective-C code can be invoked from a Unity iOS application. This application implements a very simple Bonjour client. The application consists of a Unity iOS project (Plugins/Bonjour.cs is the C# interface to the native code, while BonjourTest.js is the JS script that implements the application logic) and native code (Assets/Code) that should be added to the built XCode project.

Page last updated: 2013-02-06



iphone-Downloadable-Content

This chapter does not describe how to integrate your game with Apple's StoreKit API. It is assumed that you already have integration with StoreKit via a native code plugin.

The Apple StoreKit documentation defines four kinds of products that can be sold via the In App Purchase process:

This chapter covers the first case only and focuses mainly on the downloadable content concept. AssetBundles are recommended for implementing downloadable content in Unity and both the creation and runtime usage of AssetBundles will be covered here.

Note: AssetBundles are a Pro-only feature. Users of the basic iOS add-on will not be able to use AssetBundles in their game code.

Exporting your assets for use on iOS

It is sometimes useful to maintain separate projects for your main application and the downloadable AssetBundles that it will use. However, you should note that all scripts referenced by objects in the AssetBundle must be present in the main game executable. The project you use to create the AssetBundle must have iOS as the selected build target since the content of AssetBundle files is not compatible between iOS and other platforms.

AssetBundles are created using editor scripts - a simple example is given below:-

// C#
using UnityEngine;
using UnityEditor;


public class ExportBundle : MonoBehaviour {
	[MenuItem ("Assets/Build AssetBundle From Selection - Track dependencies")]
	static void DoExport() {
		string str = EditorUtility.SaveFilePanel("Save Bundle...", Application.dataPath, Selection.activeObject.name, "assetbundle");
		if (str.Length != 0) {
			BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, str, BuildAssetBundleOptions.CompleteAssets, BuildTarget.iPhone);
		}
	}
}



// JS
@MenuItem ("Assets/Build AssetBundle From Selection - Track dependencies")
static function ExportBundle(){

        var str : String = EditorUtility.SaveFilePanel("Save Bundle...", Application.dataPath, Selection.activeObject.name, "assetbundle");
        if (str.Length != 0){
             BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, str, BuildAssetBundleOptions.CompleteAssets, BuildTarget.iPhone);
        }
}

You should save this code in a file called ExportBundle and place it inside a folder called Editor (you can just create this if it isn't already present in the project). The script will add a menu item entitled "Build AssetBundle From Selection - Track dependencies" on the Assets menu in the editor.

The content you want to include in the bundle should be prepared in the form of prefabs. Select a prefab in the Project view and then select Assets > Build AssetBundle From Selection - Track dependencies (ie, the menu item added by the ExportBundle script). This command will bring up a save dialog where you can choose the name and location of your AssetBundle file.

Downloading your assets on iOS

Note: Apple may change the folder locations where you are permitted to write data. Always check the latest Apple documentation to be sure your application will be compliant. The following advice was correct as of early 2013.

AssetBundles can be downloaded using the WWW class and once transfer is complete, the enclosed assets can be accessed. The recommended way to download an AssetBundle is to use LoadFromCacheOrDownload as shown in the following sample:-

// C#
IEnumerator GetAssetBundle() {
	WWW download;

	string url = "http://somehost/somepath/someassetbundle.assetbundle";

	download = WWW.LoadFromCacheOrDownload(url, 0);

	yield return download;

	AssetBundle assetBundle = download.assetBundle;

	if (assetBundle != null) {
		// Alternatively you can also load an asset by name (assetBundle.Load("my asset name"))
		Object go = assetBundle.mainAsset;

		if (go != null)
			Instantiate(go);
		else
			Debug.Log("Couldn't load resource");	
	} else {
		Debug.Log("Couldn't load resource");	
	}
}


// JS
function GetAssetBundle() {
	var download : WWW;

	var url = "http://somehost/somepath/someassetbundle.assetbundle";

	var download = WWW.LoadFromCacheOrDownload (url, 0);

	yield download;

	var assetBundle = download.assetBundle;

	if (assetBundle != null) {
		// Alternatively you can also load an asset by name (assetBundle.Load("my asset name"))
		var go : Object = assetBundle.mainAsset;

		if (go != null)
			Instantiate(go);
		else
			Debug.Log("Couldn't load resource");	
	} else {
		Debug.Log("Couldn't load resource");	
	}
}

The downloaded asset bundle files are stored in the Library folder of the iOS application sandbox and have the No Backup flag set on them. This means the OS won't delete these files accidentally and these files won't be backed up to iCloud. It is good idea to keep the cache size limit low, to prevent your app from grabbing all the device's disk space.

If you need to choose exactly where the AssetBundle file is stored, you can use a standard WWW download (ie, just use the constructor instead of LoadFromCacheOrDownload) and then save the downloaded data on disk using the .NET file API. You can save required files to the Application.temporaryCachePath folder (stored in Library/Caches which is regularly "cleaned out" by the OS) or the Application.persistentDataPath folder (stored in Documents which is not cleaned out by the OS). You should set the No Backup flag on these files with iPhone.SetNoBackupFlag to prevent them being backed up to iCloud.

Note: If you don't set the No Backup flag, your app may be rejected when you submit it to the App Store.

You can access saved files by creating a WWW object with a URL in the form file:///pathtoyourapplication/Library/savedassetbundle.assetbundle:-

// C#
string cachedAssetBundle = Application.temporaryCachePath + "/savedassetbundle.assetbundle"; 
System.IO.FileStream cache = new System.IO.FileStream(cachedAssetBundle, System.IO.FileMode.Create);
cache.Write(download.bytes, 0, download.bytes.Length);
cache.Close();

iPhone.SetNoBackupFlag(cachedAssetBundle);

Debug.Log("Cache saved: " + cachedAssetBundle);


// JS
private var cachedAssetBundle : String = Application.temporaryCachePath + "/savedassetbundle.assetbundle"; 
var cache = new System.IO.FileStream(cachedAssetBundle, System.IO.FileMode.Create);
cache.Write(download.bytes, 0, download.bytes.Length);
cache.Close();

iPhone.SetNoBackupFlag(cachedAssetBundle);

Debug.Log("Cache saved: " + cachedAssetBundle);
Note: You can test the reading of stored files in the Documents folder if you enable file sharing (setting UIFileSharingEnabled to true in your Info.plist allows you to access the Documents folder from iTunes). Note that the contents of the Documents folder are cached to iCloud, so you should not use this location to store AssetBundles in the final build to be shipped. See File System Basics in the Apple iOS documentation for further details.

Page last updated: 2013-06-20



MobileCustomizeSplashScreen

iOS

Under iOS Basic, a default splash screen will be displayed while your game loads, oriented according to the Default Screen Orientation option in the Player Settings.

Users with an iOS Pro license can use any texture in the project as a splash screen. The size of the texture depends on the target device (320x480 pixels for 1-3rd gen devices, 1024x768 for iPad mini/iPad 1st/2nd gen, 2048x1536 for iPad 3th/4th gen, 640x960 for 4th gen iPhone / iPod devices and 640x1136 for 5th gen devices) and supplied textures will be scaled to fit if necessary. You can set the splash screen textures using the iOS Player Settings.

Android

Under Android Basic, a default splash screen will be displayed while your game loads, oriented according to the Default Screen Orientation option in the Player Settings.

Android Pro users can use any texture in the project as a splash screen. You can set the texture from the Splash Image section of the Android Player Settings. You should also select the Splash scaling method from the following options:-

  • Center (only scale down) will draw your image at its natural size unless it is too large, in which case it will be scaled down to fit.
  • Scale to fit (letter-boxed) will draw your image so that the longer dimension fits the screen size exactly. Empty space around the sides in the shorter dimension will be filled in black.
  • Scale to fill (cropped) will scale your image so that the shorter dimension fits the screen size exactly. The image will be cropped in the longer dimension.

Page last updated: 2013-08-12



iphone-troubleshooting

This section addresses common problems that can arise when using Unity. Each platform is dealt with separately below.

Platform Trouble Shooting

Desktop

Geforce 7300GT on OSX 10.6.4

  • Deferred rendering is disabled because materials are not displayed correctly for Geforce 7300GT on OX 10.6.4; This happens because of buggy video drivers.

On Windows x64, Unity crashes when my script throws a NullReferenceException

Script Editing

Is there a way to get rid of the welcome page in MonoDevelop?

  • Yes. In the MonoDevelop preferences, go to the Visual Style section, and uncheck "Load welcome page on startup".

Why does my script open in MonoDevelop when I have selected Visual Studio as my script editor?

  • This happens when VS reports that it failed to open your script. The most common cause for this is an external plugin (e.g. Resharper) popping up a dialog at startup, requesting input from the user - this will cause VS to report that it failed to open.

Graphics

Slow framerate and/or visual artifacts.

  • This may occur if your video card drivers are not up to date. Make sure you have the latest official drivers from your card vendor.

Shadows

I see no shadows at all!

  • Unity free supports realtime shadows (hard shadows) using one directional light. All other shadow features which Unity supports are in Unity Pro. Simpler shadow methods, like using a Projector, are still possible, of course.
  • Shadows also require certain graphics hardware support. See Shadows page for details.
  • Check if shadows are not completely disabled in Quality Settings.
  • Shadows on Android and iOS have these limitations : soft shadows are not available and in forward rendering rendering path only a single directional light can cast shadows. There is no limit to the number of lights casting shadows in the deferred rendering path.

Some of my objects do not cast or receive shadows

An object's Renderer must have Receive Shadows enabled for shadows to be rendered onto it. Also, an object must have Cast Shadows enabled in order to cast shadows on other objects (both are on by default).

Only opaque objects cast and receive shadows. This means that objects using the built-in Transparent or Particle shaders will not cast shadows. In most cases it is possible to use Transparent Cutout shaders for objects like fences, vegetation, etc. If you use custom written Shaders, they have to be pixel-lit and use the Geometry render queue. Objects using VertexLit shaders do not receive shadows but are able to cast them.

Only Pixel lights cast shadows. If you want to make sure that a light always casts shadows no matter how many other lights are in the scene, then you can set it to Force Pixel render mode (see the Light reference page).

iOS

Troubleshooting on iOS devices

There are some situations with iOS where your game can work perfectly in the Unity editor but then doesn't work or maybe doesn't even start on the actual device. The problems are often related to code or content quality. This section describes the most common scenarios.

The game stops responding after a while. Xcode shows "interrupted" in the status bar.

There are a number of reasons why this may happen. Typical causes include:

  1. Scripting errors such as using uninitialized variables, etc.
  2. Using 3rd party Thumb compiled native libraries. Such libraries trigger a known problem in the iOS SDK linker and might cause random crashes.
  3. Using generic types with value types as parameters (eg, List<int>, List<SomeStruct>, List<SomeEnum>, etc) for serializable script properties.
  4. Using reflection when managed code stripping is enabled.
  5. Errors in the native plugin interface (the managed code method signature does not match the native code function signature).

Information from the XCode Debugger console can often help detect these problems (Xcode menu: View > Debug Area > Activate Console).

The Xcode console shows "Program received signal: “SIGBUS” or EXC_BAD_ACCESS error.

This message typically appears on iOS devices when your application receives a NullReferenceException. There two ways to figure out where the fault happened:

Managed stack traces

Since version 3.4 Unity includes software-based handling of the NullReferenceException. The AOT compiler includes quick checks for null references each time a method or variable is accessed on an object. This feature affects script performance which is why it is enabled only for development builds (for basic license users it is enough to enable the "development build" option in the Build Settings dialog, while iOS pro license users additionally need to enable the "script debugging" option). If everything was done right and the fault actually is occurring in .NET code then you won't see EXC_BAD_ACCESS anymore. Instead, the .NET exception text will be printed in the Xcode console (or else your code will just handle it in a "catch" statement). Typical output might be:

Unhandled Exception: System.NullReferenceException: A null value was found where an object instance was required.
  at DayController+$handleTimeOfDay$121+$.MoveNext () [0x0035a] in DayController.js:122 

This indicates that the fault happened in the handleTimeOfDay method of the DayController class, which works as a coroutine. Also if it is script code then you will generally be told the exact line number (eg, "DayController.js:122"). The offending line might be something like the following:

 Instantiate(_imgwww.assetBundle.mainAsset);

This might happen if, say, the script accesses an asset bundle without first checking that it was downloaded correctly.

Native stack traces

Native stack traces are a much more powerful tool for fault investigation but using them requires some expertise. Also, you generally can't continue after these native (hardware memory access) faults happen. To get a native stack trace, type bt all into the Xcode Debugger Console. Carefully inspect the printed stack traces - they may contain hints about where the error occurred. You might see something like:

...
Thread 1 (thread 11523): 
#0 0x006267d0 in m_OptionsMenu_Start () 
#1 0x002e4160 in wrapper_runtime_invoke_object_runtime_invoke_void__this___object_intptr_intptr_intptr () 
#2 0x00a1dd64 in mono_jit_runtime_invoke (method=0x18b63bc, obj=0x5d10cb0, params=0x0, exc=0x2fffdd34) at /Users/mantasp/work/unity/unity-mono/External/Mono/mono/mono/mini/mini.c:4487
#3 0x0088481c in MonoBehaviour::InvokeMethodOrCoroutineChecked ()
...

First of all you should find the stack trace for "Thread 1", which is the main thread. The very first lines of the stack trace will point to the place where the error occurred. In this example, the trace indicates that the NullReferenceException happened inside the "OptionsMenu" script's "Start" method. Looking carefully at this method implementation would reveal the cause of the problem. Typically, NullReferenceExceptions happen inside the Start method when incorrect assumptions are made about initialization order. In some cases only a partial stack trace is seen on the Debugger Console:

Thread 1 (thread 11523): 
#0 0x0062564c in start ()

This indicates that native symbols were stripped during the Release build of the application. The full stack trace can be obtained with the following procedure:

  • Remove application from device.
  • Clean all targets.
  • Build and run.
  • Get stack traces again as described above.

EXC_BAD_ACCESS starts occurring when an external library is linked to the Unity iOS application.

This usually happens when an external library is compiled with the ARM Thumb instruction set. Currently such libraries are not compatible with Unity. The problem can be solved easily by recompiling the library without Thumb instructions. You can do this for the library's Xcode project with the following steps:

  • in Xcode, select "View" > "Navigators" > "Show Project Navigator" from the menu
  • select the "Unity-iPhone" project, activate "Build Settings" tab
  • in the search field enter : "Other C Flags"
  • add -mno-thumb flag there and rebuild the library.

If the library source is not available you should ask the supplier for a non-thumb version of the library.

The Xcode console shows "WARNING -> applicationDidReceiveMemoryWarning()" and the application crashes immediately afterwards

(Sometimes you might see a message like Program received signal: "0".) This warning message is often not fatal and merely indicates that iOS is low on memory and is asking applications to free up some memory. Typically, background processes like Mail will free some memory and your application can continue to run. However, if your application continues to use memory or ask for more, the OS will eventually start killing applications and yours could be one of them. Apple does not document what memory usage is safe, but empirical observations show that applications using less than 50% MB of all device RAM (like ~200-256 MB for 2nd generation ipad) do not have major memory usage problems. The main metric you should rely on is how much RAM your application uses. Your application memory usage consists of three major components:

  • application code (the OS needs to load and keep your application code in RAM, but some of it might be discarded if really needed)
  • native heap (used by the engine to store its state, your assets, etc. in RAM)
  • managed heap (used by your Mono runtime to keep C# or JavaScript objects)
  • GLES driver memory pools: textures, framebuffers, compiled shaders, etc.

Your application memory usage can be tracked by two Xcode Instruments tools: Activity Monitor, Object Allocations and VM Tracker. You can start from the Xcode Run menu: Product > Profile and then select specific tool. Activity Monitor tool shows all process statistics including Real memory which can be regarded as the total amount of RAM used by your application. Note: OS and device HW version combination might noticeably affect memory usage numbers, so you should be careful when comparing numbers obtained on different devices.

Note: The internal profiler shows only the heap allocated by .NET scripts. Total memory usage can be determined via Xcode Instruments as shown above. This figure includes parts of the application binary, some standard framework buffers, Unity engine internal state buffers, the .NET runtime heap (number printed by internal profiler), GLES driver heap and some other miscellaneous stuff.

The other tool displays all allocations made by your application and includes both native heap and managed heap statistics (don't forget to check the Created and still living box to get the current state of the application). The important statistic is the Net bytes value.

To keep memory usage low:

  • Reduce the application binary size by using the strongest iOS stripping options (Advanced license feature), and avoid unnecessary dependencies on different .NET libraries. See the player settings and player size optimization manual pages for further details.
  • Reduce the size of your content. Use PVRTC compression for textures and use low poly models. See the manual page about reducing file size for more information.
  • Don't allocate more memory than necessary in your scripts. Track mono heap size and usage with the internal profiler
  • Note: with Unity 3.0, the scene loading implementation has changed significantly and now all scene assets are preloaded. This results in fewer hiccups when instantiating game objects. If you need more fine-grained control of asset loading and unloading during gameplay, you should use Resources.Load and Object.Destroy.

Querying the OS about the amount of free memory may seem like a good idea to evaluate how well your application is performing. However, the free memory statistic is likely to be unreliable since the OS uses a lot of dynamic buffers and caches. The only reliable approach is to keep track of memory consumption for your application and use that as the main metric. Pay attention to how the graphs from the tools described above change over time, especially after loading new levels.

The game runs correctly when launched from Xcode but crashes while loading the first level when launched manually on the device.

There could be several reasons for this. You need to inspect the device logs to get more details. Connect the device to your Mac, launch Xcode and select Window > Organizer from the menu. Select your device in the Organizer's left toolbar, then click on the "Console" tab and review the latest messages carefully. Additionally, you may need to investigate crash reports. You can find out how to obtain crash reports here: http://developer.apple.com/iphone/library/technotes/tn2008/tn2151.html.

The Xcode Organizer console contains the message "killed by SpringBoard".

There is a poorly-documented time limit for an iOS application to render its first frames and process input. If your application exceeds this limit, it will be killed by SpringBoard. This may happen in an application with a first scene which is too large, for example. To avoid this problem, it is advisable to create a small initial scene which just displays a splash screen, waits a frame or two with yield and then starts loading the real scene. This can be done with code as simple as the following:

 
function Start () {
    yield;
    Application.LoadLevel("Test");
}

Type.GetProperty() / Type.GetValue() cause crashes on the device

Currently Type.GetProperty() and Type.GetValue() are supported only for the .NET 2.0 Subset profile. You can select the .NET API compatibility level in the Player Settings.

Note: Type.GetProperty() and Type.GetValue() might be incompatible with managed code stripping and might need to be excluded (you can supply a custom non-strippable type list during the stripping process to accomplish this). For further details, see the iOS player size optimization guide.

The game crashes with the error message "ExecutionEngineException: Attempting to JIT compile method 'SometType`1<SomeValueType>:.ctor ()' while running with --aot-only."

The Mono .NET implementation for iOS is based on AOT (ahead of time compilation to native code) technology, which has its limitations. It compiles only those generic type methods (where a value type is used as a generic parameter) which are explicitly used by other code. When such methods are used only via reflection or from native code (ie, the serialization system) then they get skipped during AOT compilation. The AOT compiler can be hinted to include code by adding a dummy method somewhere in the script code. This can refer to the missing methods and so get them compiled ahead of time.

void _unusedMethod()
{
    var tmp = new SomeType<SomeValueType>();
}

Note: value types are basic types, enums and structs.

Various crashes occur on the device when a combination of System.Security.Cryptography and managed code stripping is used

.NET Cryptography services rely heavily on reflection and so are not compatible with managed code stripping since this involves static code analysis. Sometimes the easiest solution to the crashes is to exclude the whole System.Security.Crypography namespace from the stripping process.

The stripping process can be customized by adding a custom link.xml file to the Assets folder of your Unity project. This specifies which types and namespaces should be excluded from stripping. Further details can be found in the iOS player size optimization guide.

link.xml

<linker>
       <assembly fullname="mscorlib">
               <namespace fullname="System.Security.Cryptography" preserve="all"/>
       </assembly>
</linker>

Application crashes when using System.Security.Cryptography.MD5 with managed code stripping

You might consider advice listed above or can work around this problem by adding extra reference to specific class to your script code:

object obj = new MD5CryptoServiceProvider();

"Ran out of trampolines of type 0/1/2" runtime error

This error usually happens if you use lots of recursive generics. You can hint to the AOT compiler to allocate more trampolines of type 0, type 1 or type 2. Additional AOT compiler command line options can be specified in the "Other Settings" section of the Player Settings. For type 1 trampolines, specify nrgctx-trampolines=ABCD, where ABCD is the number of new trampolines required (i.e. 4096). For type 2 trampolines specify nimt-trampolines=ABCD and for type 0 trampolines specify ntrampolines=ABCD.

After upgrading Xcode Unity iOS runtime fails with message "You are using Unity iPhone Basic. You are not allowed to remove the Unity splash screen from your game"

With some latest Xcode releases there were changes introduced in PNG compression and optimization tool. These changes might cause false positives in Unity iOS runtime checks for splash screen modifications. If you encounter such problems try upgrading Unity to the latest publicly available version. If it does not help you might consider following workaround:

  • Replace your Xcode project from scratch when building from Unity (instead of appending it)
  • Delete already installed project from device
  • Clean project in Xcode (Product->Clean)
  • Clear Xcode's Derived Data folders (Xcode->Preferences->Locations)

If this still does not help try disabling PNG re-compression in Xcode:

  • Open your Xcode project
  • Select "Unity-iPhone" project there
  • Select "Build Settings" tab there
  • Look for "Compress PNG files" option and set it to NO

App Store submission fails with "iPhone/iPod Touch: application executable is missing a required architecture. At least one of the following architecture(s) must be present: armv6" message

You might get such message when updating already existing application, which previously was submitted with armv6 support. Unity 4.x and Xcode 4.5 does not support armv6 platform anymore. To solve submission problem just set Target OS Version in Unity Player Settings to 4.3 or higher.

WWW downloads are working fine in Unity Editor and on Android, but not on iOS

Most common mistake is to assume that WWW downloads are always happening on separate thread. On some platforms this might be true, but you should not take it for granted. Best way to track WWW status is either to use yield statement or check status in Update method. You should not use busy while loops for that.

"PlayerLoop called recursively!" error occurs when using Cocoa via a native function called from a script

Some operations with the UI will result in iOS redrawing the window immediately (the most common example is adding a UIView with a UIViewController to the main UIWindow). If you call a native function from a script, it will happen inside Unity's PlayerLoop, resulting in PlayerLoop being called recursively. In such cases, you should consider using the performSelectorOnMainThread method with waitUntilDone set to false. It will inform iOS to schedule the operation to run between Unity's PlayerLoop calls.

Profiler or Debugger unable to see game running on iOS device

  • Check that you have built a Development build, and ticked the "Enable Script Debugging" and "Autoconnect profiler" boxes (as appropriate).
  • The application running on the device will make a multicast broadcast to 225.0.0.222 on UDP port 54997. Check that your network settings allow this traffic. Then, the profiler will make a connection to the remote device on a port in the range 55000 - 55511 to fetch profiler data from the device. These ports will need to be open for UDP access.

Missing DLLs

If your application runs ok in editor but you get errors in your iOS project this may be caused by missing DLLs (e.g. I18N.dll, I19N.West.dll). In this case, try copying those dlls from within the Unity.app to your project's Assets/Plugins folder. The location of the DLLs within the unity app is:

 Unity.app/Contents/Frameworks/Mono/lib/mono/unity 

You should then also check the stripping level of your project to ensure the classes in the DLLs aren't being removed when the build is optimised. Refer to the iOS Optimisation Page for more information on iOS Stripping Levels.

Xcode Debugger console reports: ExecutionEngineException: Attempting to JIT compile method '(wrapper native-to-managed) Test:TestFunc (int)' while running with --aot-only

Typically such message is received when managed function delegate is passed to the native function, but required wrapper code wasn't generated when building application. You can help AOT compiler by hinting which methods will be passed as delegates to the native code. This can be done by adding "MonoPInvokeCallbackAttribute" custom attribute. Currently only static methods can be passed as delegates to the native code.

Sample code:

using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;
using AOT;

public class NewBehaviourScript : MonoBehaviour {

	[DllImport ("__Internal")]
	private static extern void DoSomething (NoParamDelegate del1, StringParamDelegate del2);

	delegate void NoParamDelegate ();
	delegate void StringParamDelegate (string str);

	[MonoPInvokeCallback (typeof (NoParamDelegate))]
	public static void NoParamCallback()
	{
		Debug.Log ("Hello from NoParamCallback");
	}

	[MonoPInvokeCallback (typeof (StringParamDelegate))]
	public static void StringParamCallback(string str)
	{
		Debug.Log (string.Format ("Hello from StringParamCallback {0}", str));
	}

	// Use this for initialization
	void Start () {
		DoSomething(NoParamCallback, StringParamCallback);
	}
}

Xcode throws compilation error: "ld : unable to insert branch island. No insertion point available. for architecture armv7", "clang: error: linker command failed with exit code 1 (use -v to see invocation)"

That error usually means there is just too much code in single module. Typically it is caused by having lots of script code or having big external .NET assemblies included into build. And enabling script debugging might make things worse, because it adds quite few additional instructions to each function, so it is easier to hit that limit.

Enabling managed code stripping in player settings might help with this problem, especially if big external .NET assemblies are involved. But if the issue persists then the best solution is to split user script code into multiple assemblies. The easiest way to this is move some code to Plugins folder. Code at this location is put to different assembly. Also check the information about how special folder names affect script compilation:

Android

Troubleshooting Android development

"No Platforms Found" error:

  1. Uninstall the current Android SDK and make sure that you don't have more than one copy of it.
  2. Update Java with a stable version. Bear in mind the latest version shouldn't have conflicts, but users have experienced problems in the past.
  3. Download a fresh copy of the latest ADT Bundle and install it following the instructions. This should configure the development tools correctly: http://developer.android.com/sdk/index.html
  4. Configure Unity with the installed Android SDK.

Unity fails to install your application to your device

  1. Verify that your computer can actually see and communicate with the device. See the Publishing Builds page for further details.
  2. Check the error message in the Unity console. This will often help diagnose the problem.

If you get an error saying "Unable to install APK, protocol failure" during a build then this indicates that the device is connected to a low-power USB port (perhaps a port on a keyboard or other peripheral). If this happens, try connecting the device to a USB port on the computer itself.

Your application crashes immediately after launch.

  1. Ensure that you are not trying to use NativeActivity with devices that do not support it.
  2. Try removing any native plugins you have.
  3. Try disabling stripping.
  4. Use adb logcat to get the crash report from your device.

Building DEX Failed

This is an error which will produce a message similar to the following:-

Building DEX Failed!
G:\Unity\JavaPluginSample\Temp/StagingArea> java -Xmx1024M 
-Djava.ext.dirs="G:/AndroidSDK/android-sdk_r09-windows\platform-tools/lib/" 
-jar "G:/AndroidSDK/android-sdk_r09-windows\platform-tools/lib/dx.jar" 
--dex --verbose --output=bin/classes.dex bin/classes.jar plugins
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

This is usually caused by having the wrong version of Java installed on your machine. Updating your Java installation to the latest version will generally solve this issue.

The game crashes after a couple of seconds when playing video

Make sure Settings->Developer Options->Don't keep activities isn't enabled on the phone. The video player is its own activity and therefore the regular game activity will be destroyed if the video player is activated.

My game quits when I press the sleep button

Change the activity tag in the AndroidManifest.xml to contain android:configChanges tag as described here.

An example activity tag might look something like this:-

<activity android:name=".AdMobTestActivity"
                  android:label="@string/app_name"
                  android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Page last updated: 2013-08-07



iphone-bugreporting

Before submitting a bug report, please check the iOS Troubleshooting page, where you will find solutions to common crashes and other problems.

If your application crashes in the Xcode debugger then you can add valuable information to your bug report as follows:-

  1. Click Continue (Run->Continue) twice
  2. Open the debugger console (Run->Console) and enter (in the console): thread apply all bt
  3. Copy all console output and send it together with your bugreport.

If your application crashes on the iOS device then you should retrieve the crash report as described here on Apple's website. Please attach the crash report, your built application and console log to your bug report before submitting.

Page last updated: 2011-11-08



android-GettingStarted

Building games for a device running Android OS requires an approach similar to that for iOS development. However, the hardware is not completely standardized across all devices, and this raises issues that don't occur in iOS development. There are some feature differences in the Android version of Unity just as there are with the iOS version.

Setting up your Android Developer environment

You will need to have your Android developer environment set up before you can test your Unity games on the device. This involves downloading and installing the Android SDK with the different Android plaforms and adding your physical device to your system (this is done a bit differently depending on whether you are developing on Windows or Mac). This setup process is explained on the Android developer website, and there may be additional information provided by the manufacturer of your device. Since this is a complex process, we've provided a basic outline of the tasks that must be completed before you can run code on your Android device or in the Android emulator. However, the best thing to do is follow the instructions step-by-step from the Android developer portal.

Access Android Functionality

Unity Android provides scripting APIs to access various input data and settings. You can find out more about the available classes on the Android scripting page.

Exposing Native C, C++ or Java Code to Scripts

Unity Android allows you to call custom functions written in C/C++ directly from C# scripts (Java functions can be called indirectly). To find out how to make functions from native code accessible from Unity, visit the Android plugins page.

Occlusion Culling

Unity includes support for occlusion culling which is a particularly valuable optimization on mobile platforms. More information can be found on the occlusion culling page.

Splash Screen Customization

The splash screen displayed while the game launches can be customized - see this page for further details.

Troubleshooting and Bug Reports

There are many reasons why your application may crash or fail to work as you expected. Our Android troubleshooting guide will help you get to the bottom of bugs as quickly as possible. If, after consulting the guide, you suspect the problem is internal to Unity then you should file a bug report - see this page for details on how to do this.

How Unity Android Differs from Desktop Unity

Strongly Typed JavaScript

For performance reasons, dynamic typing in JavaScript is always turned off in Unity Android, as if #pragma strict were applied automatically to all scripts. This is important to know if you start with a project originally developed for the desktop platforms since you may find you get unexpected compile errors when switching to Android; dynamic typing is the first thing to investigate. These errors are usually easy to fix if you make sure all variables are explicitly typed or use type inference on initialization.

ETC as Recommended Texture Compression

Although Unity Android does support DXT/PVRTC/ATC textures, Unity will decompress the textures into RGB(A) format at runtime if those compression methods are not supported by the particular device in use. This could have an impact on the GPU rendering speed and it is recommended to use the ETC format instead. ETC is the de facto standard compression format on Android, and should be supported on all post 2.0 devices. However, ETC does not support an alpha channel and RGBA 16-bit will sometimes be the best trade-off between size, quality and rendering speed where alpha is required.

It is also possible to create separate android distribution archives (.apk) for each of the DXT/PVRTC/ATC formats, and let the Android Market's filtering system select the correct archives for different devices (see Publishing Builds for Android).

Movie Playback

Movie textures are not supported on Android, but a full-screen streaming playback is provided via scripting functions. To learn about supported file formats and scripting API, consult the movie page or the Android supported media formats page.

Page last updated: 2013-10-10



android-sdksetup

There are some steps you must follow before you can build and run any code on your Android device. This is true regardless of whether you use Unity or write Android applications from scratch.

1. Download the Android SDK

Go to the Android Developer SDK webpage. Download and unpack the latest Android SDK.

2. Installing the Android SDK

Follow the instructions under Installing the SDK (although you can freely skip the optional parts relating to Eclipse). In step 4 of Installing the SDK be sure to add at least one Android platform with API level equal to or higher than 9 (Platform 2.3 or greater), the Platform Tools, and the USB drivers if you're using Windows.

3. Get the device recognized by your system

This can be tricky, especially under Windows based systems where drivers tend to be a problem. Also, your device may come with additional information or specific drivers from the manufacturer.

For Windows: If the Android device is automatically recognized by the system you still might need to update the drivers with the ones that came with the Android SDK. This is done through the Windows Device Manager.

If the device is not recognized automatically use the drivers from the Android SDK, or any specific drivers provided by the manufacturer.
Additional info can be found here: USB Drivers for Windows

For Mac: If you're developing on Mac OSX then no additional drivers are usually required.

Note: Don't forget to turn on "USB Debugging" on your device. Go to Settings -> Developer options, then enable USB debugging. As of Android Jelly Bean 4.2 the Developer options are hidden by default. To enable them tap on Settings -> About Phone -> Build Version multiple times. Then you will be able to access the Settings -> Developer options.

If you are unsure whether your device is properly installed on your system, please read the trouble-shooting page for details.

4. Add the Android SDK path to Unity

The first time you build a project for Android (or if Unity later fails to locate the SDK) you will be asked to locate the folder where you installed the Android SDK (you should select the root folder of the SDK installation). The location of the Android SDK can also be changed in the editor by selecting Unity > Preferences from the menu and then clicking on External Tools in the preferences window.

Page last updated: 2013-07-18



android-remote

Android Remote is a Android application that makes your device act as a remote control for the project in Unity. This is useful for rapid development when you don't want to compile and deploy your project to device for each change.

How to use Android remote

To use Android Remote, you should firstly make sure that you have the latest Android SDK installed (this is necessary to set up port-forwarding on the device). Then, connect the device to your computer with a USB cable and launch the Android Remote app. When you press Play in the Unity editor, the device will act as a remote control and will pass accelerometer and touch input events to the running game.

Page last updated: 2011-11-23



android-troubleshooting

This section addresses common problems that can arise when using Unity. Each platform is dealt with separately below.

Platform Trouble Shooting

Desktop

Geforce 7300GT on OSX 10.6.4

  • Deferred rendering is disabled because materials are not displayed correctly for Geforce 7300GT on OX 10.6.4; This happens because of buggy video drivers.

On Windows x64, Unity crashes when my script throws a NullReferenceException

Script Editing

Is there a way to get rid of the welcome page in MonoDevelop?

  • Yes. In the MonoDevelop preferences, go to the Visual Style section, and uncheck "Load welcome page on startup".

Why does my script open in MonoDevelop when I have selected Visual Studio as my script editor?

  • This happens when VS reports that it failed to open your script. The most common cause for this is an external plugin (e.g. Resharper) popping up a dialog at startup, requesting input from the user - this will cause VS to report that it failed to open.

Graphics

Slow framerate and/or visual artifacts.

  • This may occur if your video card drivers are not up to date. Make sure you have the latest official drivers from your card vendor.

Shadows

I see no shadows at all!

  • Unity free supports realtime shadows (hard shadows) using one directional light. All other shadow features which Unity supports are in Unity Pro. Simpler shadow methods, like using a Projector, are still possible, of course.
  • Shadows also require certain graphics hardware support. See Shadows page for details.
  • Check if shadows are not completely disabled in Quality Settings.
  • Shadows on Android and iOS have these limitations : soft shadows are not available and in forward rendering rendering path only a single directional light can cast shadows. There is no limit to the number of lights casting shadows in the deferred rendering path.

Some of my objects do not cast or receive shadows

An object's Renderer must have Receive Shadows enabled for shadows to be rendered onto it. Also, an object must have Cast Shadows enabled in order to cast shadows on other objects (both are on by default).

Only opaque objects cast and receive shadows. This means that objects using the built-in Transparent or Particle shaders will not cast shadows. In most cases it is possible to use Transparent Cutout shaders for objects like fences, vegetation, etc. If you use custom written Shaders, they have to be pixel-lit and use the Geometry render queue. Objects using VertexLit shaders do not receive shadows but are able to cast them.

Only Pixel lights cast shadows. If you want to make sure that a light always casts shadows no matter how many other lights are in the scene, then you can set it to Force Pixel render mode (see the Light reference page).

iOS

Troubleshooting on iOS devices

There are some situations with iOS where your game can work perfectly in the Unity editor but then doesn't work or maybe doesn't even start on the actual device. The problems are often related to code or content quality. This section describes the most common scenarios.

The game stops responding after a while. Xcode shows "interrupted" in the status bar.

There are a number of reasons why this may happen. Typical causes include:

  1. Scripting errors such as using uninitialized variables, etc.
  2. Using 3rd party Thumb compiled native libraries. Such libraries trigger a known problem in the iOS SDK linker and might cause random crashes.
  3. Using generic types with value types as parameters (eg, List<int>, List<SomeStruct>, List<SomeEnum>, etc) for serializable script properties.
  4. Using reflection when managed code stripping is enabled.
  5. Errors in the native plugin interface (the managed code method signature does not match the native code function signature).

Information from the XCode Debugger console can often help detect these problems (Xcode menu: View > Debug Area > Activate Console).

The Xcode console shows "Program received signal: “SIGBUS” or EXC_BAD_ACCESS error.

This message typically appears on iOS devices when your application receives a NullReferenceException. There two ways to figure out where the fault happened:

Managed stack traces

Since version 3.4 Unity includes software-based handling of the NullReferenceException. The AOT compiler includes quick checks for null references each time a method or variable is accessed on an object. This feature affects script performance which is why it is enabled only for development builds (for basic license users it is enough to enable the "development build" option in the Build Settings dialog, while iOS pro license users additionally need to enable the "script debugging" option). If everything was done right and the fault actually is occurring in .NET code then you won't see EXC_BAD_ACCESS anymore. Instead, the .NET exception text will be printed in the Xcode console (or else your code will just handle it in a "catch" statement). Typical output might be:

Unhandled Exception: System.NullReferenceException: A null value was found where an object instance was required.
  at DayController+$handleTimeOfDay$121+$.MoveNext () [0x0035a] in DayController.js:122 

This indicates that the fault happened in the handleTimeOfDay method of the DayController class, which works as a coroutine. Also if it is script code then you will generally be told the exact line number (eg, "DayController.js:122"). The offending line might be something like the following:

 Instantiate(_imgwww.assetBundle.mainAsset);

This might happen if, say, the script accesses an asset bundle without first checking that it was downloaded correctly.

Native stack traces

Native stack traces are a much more powerful tool for fault investigation but using them requires some expertise. Also, you generally can't continue after these native (hardware memory access) faults happen. To get a native stack trace, type bt all into the Xcode Debugger Console. Carefully inspect the printed stack traces - they may contain hints about where the error occurred. You might see something like:

...
Thread 1 (thread 11523): 
#0 0x006267d0 in m_OptionsMenu_Start () 
#1 0x002e4160 in wrapper_runtime_invoke_object_runtime_invoke_void__this___object_intptr_intptr_intptr () 
#2 0x00a1dd64 in mono_jit_runtime_invoke (method=0x18b63bc, obj=0x5d10cb0, params=0x0, exc=0x2fffdd34) at /Users/mantasp/work/unity/unity-mono/External/Mono/mono/mono/mini/mini.c:4487
#3 0x0088481c in MonoBehaviour::InvokeMethodOrCoroutineChecked ()
...

First of all you should find the stack trace for "Thread 1", which is the main thread. The very first lines of the stack trace will point to the place where the error occurred. In this example, the trace indicates that the NullReferenceException happened inside the "OptionsMenu" script's "Start" method. Looking carefully at this method implementation would reveal the cause of the problem. Typically, NullReferenceExceptions happen inside the Start method when incorrect assumptions are made about initialization order. In some cases only a partial stack trace is seen on the Debugger Console:

Thread 1 (thread 11523): 
#0 0x0062564c in start ()

This indicates that native symbols were stripped during the Release build of the application. The full stack trace can be obtained with the following procedure:

  • Remove application from device.
  • Clean all targets.
  • Build and run.
  • Get stack traces again as described above.

EXC_BAD_ACCESS starts occurring when an external library is linked to the Unity iOS application.

This usually happens when an external library is compiled with the ARM Thumb instruction set. Currently such libraries are not compatible with Unity. The problem can be solved easily by recompiling the library without Thumb instructions. You can do this for the library's Xcode project with the following steps:

  • in Xcode, select "View" > "Navigators" > "Show Project Navigator" from the menu
  • select the "Unity-iPhone" project, activate "Build Settings" tab
  • in the search field enter : "Other C Flags"
  • add -mno-thumb flag there and rebuild the library.

If the library source is not available you should ask the supplier for a non-thumb version of the library.

The Xcode console shows "WARNING -> applicationDidReceiveMemoryWarning()" and the application crashes immediately afterwards

(Sometimes you might see a message like Program received signal: "0".) This warning message is often not fatal and merely indicates that iOS is low on memory and is asking applications to free up some memory. Typically, background processes like Mail will free some memory and your application can continue to run. However, if your application continues to use memory or ask for more, the OS will eventually start killing applications and yours could be one of them. Apple does not document what memory usage is safe, but empirical observations show that applications using less than 50% MB of all device RAM (like ~200-256 MB for 2nd generation ipad) do not have major memory usage problems. The main metric you should rely on is how much RAM your application uses. Your application memory usage consists of three major components:

  • application code (the OS needs to load and keep your application code in RAM, but some of it might be discarded if really needed)
  • native heap (used by the engine to store its state, your assets, etc. in RAM)
  • managed heap (used by your Mono runtime to keep C# or JavaScript objects)
  • GLES driver memory pools: textures, framebuffers, compiled shaders, etc.

Your application memory usage can be tracked by two Xcode Instruments tools: Activity Monitor, Object Allocations and VM Tracker. You can start from the Xcode Run menu: Product > Profile and then select specific tool. Activity Monitor tool shows all process statistics including Real memory which can be regarded as the total amount of RAM used by your application. Note: OS and device HW version combination might noticeably affect memory usage numbers, so you should be careful when comparing numbers obtained on different devices.

Note: The internal profiler shows only the heap allocated by .NET scripts. Total memory usage can be determined via Xcode Instruments as shown above. This figure includes parts of the application binary, some standard framework buffers, Unity engine internal state buffers, the .NET runtime heap (number printed by internal profiler), GLES driver heap and some other miscellaneous stuff.

The other tool displays all allocations made by your application and includes both native heap and managed heap statistics (don't forget to check the Created and still living box to get the current state of the application). The important statistic is the Net bytes value.

To keep memory usage low:

  • Reduce the application binary size by using the strongest iOS stripping options (Advanced license feature), and avoid unnecessary dependencies on different .NET libraries. See the player settings and player size optimization manual pages for further details.
  • Reduce the size of your content. Use PVRTC compression for textures and use low poly models. See the manual page about reducing file size for more information.
  • Don't allocate more memory than necessary in your scripts. Track mono heap size and usage with the internal profiler
  • Note: with Unity 3.0, the scene loading implementation has changed significantly and now all scene assets are preloaded. This results in fewer hiccups when instantiating game objects. If you need more fine-grained control of asset loading and unloading during gameplay, you should use Resources.Load and Object.Destroy.

Querying the OS about the amount of free memory may seem like a good idea to evaluate how well your application is performing. However, the free memory statistic is likely to be unreliable since the OS uses a lot of dynamic buffers and caches. The only reliable approach is to keep track of memory consumption for your application and use that as the main metric. Pay attention to how the graphs from the tools described above change over time, especially after loading new levels.

The game runs correctly when launched from Xcode but crashes while loading the first level when launched manually on the device.

There could be several reasons for this. You need to inspect the device logs to get more details. Connect the device to your Mac, launch Xcode and select Window > Organizer from the menu. Select your device in the Organizer's left toolbar, then click on the "Console" tab and review the latest messages carefully. Additionally, you may need to investigate crash reports. You can find out how to obtain crash reports here: http://developer.apple.com/iphone/library/technotes/tn2008/tn2151.html.

The Xcode Organizer console contains the message "killed by SpringBoard".

There is a poorly-documented time limit for an iOS application to render its first frames and process input. If your application exceeds this limit, it will be killed by SpringBoard. This may happen in an application with a first scene which is too large, for example. To avoid this problem, it is advisable to create a small initial scene which just displays a splash screen, waits a frame or two with yield and then starts loading the real scene. This can be done with code as simple as the following:

 
function Start () {
    yield;
    Application.LoadLevel("Test");
}

Type.GetProperty() / Type.GetValue() cause crashes on the device

Currently Type.GetProperty() and Type.GetValue() are supported only for the .NET 2.0 Subset profile. You can select the .NET API compatibility level in the Player Settings.

Note: Type.GetProperty() and Type.GetValue() might be incompatible with managed code stripping and might need to be excluded (you can supply a custom non-strippable type list during the stripping process to accomplish this). For further details, see the iOS player size optimization guide.

The game crashes with the error message "ExecutionEngineException: Attempting to JIT compile method 'SometType`1<SomeValueType>:.ctor ()' while running with --aot-only."

The Mono .NET implementation for iOS is based on AOT (ahead of time compilation to native code) technology, which has its limitations. It compiles only those generic type methods (where a value type is used as a generic parameter) which are explicitly used by other code. When such methods are used only via reflection or from native code (ie, the serialization system) then they get skipped during AOT compilation. The AOT compiler can be hinted to include code by adding a dummy method somewhere in the script code. This can refer to the missing methods and so get them compiled ahead of time.

void _unusedMethod()
{
    var tmp = new SomeType<SomeValueType>();
}

Note: value types are basic types, enums and structs.

Various crashes occur on the device when a combination of System.Security.Cryptography and managed code stripping is used

.NET Cryptography services rely heavily on reflection and so are not compatible with managed code stripping since this involves static code analysis. Sometimes the easiest solution to the crashes is to exclude the whole System.Security.Crypography namespace from the stripping process.

The stripping process can be customized by adding a custom link.xml file to the Assets folder of your Unity project. This specifies which types and namespaces should be excluded from stripping. Further details can be found in the iOS player size optimization guide.

link.xml

<linker>
       <assembly fullname="mscorlib">
               <namespace fullname="System.Security.Cryptography" preserve="all"/>
       </assembly>
</linker>

Application crashes when using System.Security.Cryptography.MD5 with managed code stripping

You might consider advice listed above or can work around this problem by adding extra reference to specific class to your script code:

object obj = new MD5CryptoServiceProvider();

"Ran out of trampolines of type 0/1/2" runtime error

This error usually happens if you use lots of recursive generics. You can hint to the AOT compiler to allocate more trampolines of type 0, type 1 or type 2. Additional AOT compiler command line options can be specified in the "Other Settings" section of the Player Settings. For type 1 trampolines, specify nrgctx-trampolines=ABCD, where ABCD is the number of new trampolines required (i.e. 4096). For type 2 trampolines specify nimt-trampolines=ABCD and for type 0 trampolines specify ntrampolines=ABCD.

After upgrading Xcode Unity iOS runtime fails with message "You are using Unity iPhone Basic. You are not allowed to remove the Unity splash screen from your game"

With some latest Xcode releases there were changes introduced in PNG compression and optimization tool. These changes might cause false positives in Unity iOS runtime checks for splash screen modifications. If you encounter such problems try upgrading Unity to the latest publicly available version. If it does not help you might consider following workaround:

  • Replace your Xcode project from scratch when building from Unity (instead of appending it)
  • Delete already installed project from device
  • Clean project in Xcode (Product->Clean)
  • Clear Xcode's Derived Data folders (Xcode->Preferences->Locations)

If this still does not help try disabling PNG re-compression in Xcode:

  • Open your Xcode project
  • Select "Unity-iPhone" project there
  • Select "Build Settings" tab there
  • Look for "Compress PNG files" option and set it to NO

App Store submission fails with "iPhone/iPod Touch: application executable is missing a required architecture. At least one of the following architecture(s) must be present: armv6" message

You might get such message when updating already existing application, which previously was submitted with armv6 support. Unity 4.x and Xcode 4.5 does not support armv6 platform anymore. To solve submission problem just set Target OS Version in Unity Player Settings to 4.3 or higher.

WWW downloads are working fine in Unity Editor and on Android, but not on iOS

Most common mistake is to assume that WWW downloads are always happening on separate thread. On some platforms this might be true, but you should not take it for granted. Best way to track WWW status is either to use yield statement or check status in Update method. You should not use busy while loops for that.

"PlayerLoop called recursively!" error occurs when using Cocoa via a native function called from a script

Some operations with the UI will result in iOS redrawing the window immediately (the most common example is adding a UIView with a UIViewController to the main UIWindow). If you call a native function from a script, it will happen inside Unity's PlayerLoop, resulting in PlayerLoop being called recursively. In such cases, you should consider using the performSelectorOnMainThread method with waitUntilDone set to false. It will inform iOS to schedule the operation to run between Unity's PlayerLoop calls.

Profiler or Debugger unable to see game running on iOS device

  • Check that you have built a Development build, and ticked the "Enable Script Debugging" and "Autoconnect profiler" boxes (as appropriate).
  • The application running on the device will make a multicast broadcast to 225.0.0.222 on UDP port 54997. Check that your network settings allow this traffic. Then, the profiler will make a connection to the remote device on a port in the range 55000 - 55511 to fetch profiler data from the device. These ports will need to be open for UDP access.

Missing DLLs

If your application runs ok in editor but you get errors in your iOS project this may be caused by missing DLLs (e.g. I18N.dll, I19N.West.dll). In this case, try copying those dlls from within the Unity.app to your project's Assets/Plugins folder. The location of the DLLs within the unity app is:

 Unity.app/Contents/Frameworks/Mono/lib/mono/unity 

You should then also check the stripping level of your project to ensure the classes in the DLLs aren't being removed when the build is optimised. Refer to the iOS Optimisation Page for more information on iOS Stripping Levels.

Xcode Debugger console reports: ExecutionEngineException: Attempting to JIT compile method '(wrapper native-to-managed) Test:TestFunc (int)' while running with --aot-only

Typically such message is received when managed function delegate is passed to the native function, but required wrapper code wasn't generated when building application. You can help AOT compiler by hinting which methods will be passed as delegates to the native code. This can be done by adding "MonoPInvokeCallbackAttribute" custom attribute. Currently only static methods can be passed as delegates to the native code.

Sample code:

using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;
using AOT;

public class NewBehaviourScript : MonoBehaviour {

	[DllImport ("__Internal")]
	private static extern void DoSomething (NoParamDelegate del1, StringParamDelegate del2);

	delegate void NoParamDelegate ();
	delegate void StringParamDelegate (string str);

	[MonoPInvokeCallback (typeof (NoParamDelegate))]
	public static void NoParamCallback()
	{
		Debug.Log ("Hello from NoParamCallback");
	}

	[MonoPInvokeCallback (typeof (StringParamDelegate))]
	public static void StringParamCallback(string str)
	{
		Debug.Log (string.Format ("Hello from StringParamCallback {0}", str));
	}

	// Use this for initialization
	void Start () {
		DoSomething(NoParamCallback, StringParamCallback);
	}
}

Xcode throws compilation error: "ld : unable to insert branch island. No insertion point available. for architecture armv7", "clang: error: linker command failed with exit code 1 (use -v to see invocation)"

That error usually means there is just too much code in single module. Typically it is caused by having lots of script code or having big external .NET assemblies included into build. And enabling script debugging might make things worse, because it adds quite few additional instructions to each function, so it is easier to hit that limit.

Enabling managed code stripping in player settings might help with this problem, especially if big external .NET assemblies are involved. But if the issue persists then the best solution is to split user script code into multiple assemblies. The easiest way to this is move some code to Plugins folder. Code at this location is put to different assembly. Also check the information about how special folder names affect script compilation:

Android

Troubleshooting Android development

"No Platforms Found" error:

  1. Uninstall the current Android SDK and make sure that you don't have more than one copy of it.
  2. Update Java with a stable version. Bear in mind the latest version shouldn't have conflicts, but users have experienced problems in the past.
  3. Download a fresh copy of the latest ADT Bundle and install it following the instructions. This should configure the development tools correctly: http://developer.android.com/sdk/index.html
  4. Configure Unity with the installed Android SDK.

Unity fails to install your application to your device

  1. Verify that your computer can actually see and communicate with the device. See the Publishing Builds page for further details.
  2. Check the error message in the Unity console. This will often help diagnose the problem.

If you get an error saying "Unable to install APK, protocol failure" during a build then this indicates that the device is connected to a low-power USB port (perhaps a port on a keyboard or other peripheral). If this happens, try connecting the device to a USB port on the computer itself.

Your application crashes immediately after launch.

  1. Ensure that you are not trying to use NativeActivity with devices that do not support it.
  2. Try removing any native plugins you have.
  3. Try disabling stripping.
  4. Use adb logcat to get the crash report from your device.

Building DEX Failed

This is an error which will produce a message similar to the following:-

Building DEX Failed!
G:\Unity\JavaPluginSample\Temp/StagingArea> java -Xmx1024M 
-Djava.ext.dirs="G:/AndroidSDK/android-sdk_r09-windows\platform-tools/lib/" 
-jar "G:/AndroidSDK/android-sdk_r09-windows\platform-tools/lib/dx.jar" 
--dex --verbose --output=bin/classes.dex bin/classes.jar plugins
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

This is usually caused by having the wrong version of Java installed on your machine. Updating your Java installation to the latest version will generally solve this issue.

The game crashes after a couple of seconds when playing video

Make sure Settings->Developer Options->Don't keep activities isn't enabled on the phone. The video player is its own activity and therefore the regular game activity will be destroyed if the video player is activated.

My game quits when I press the sleep button

Change the activity tag in the AndroidManifest.xml to contain android:configChanges tag as described here.

An example activity tag might look something like this:-

<activity android:name=".AdMobTestActivity"
                  android:label="@string/app_name"
                  android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Page last updated: 2013-08-07



android-bugreporting

Before submitting a bug with just "it crashes" in the message body, please look through the Troubleshooting Android development page first.

At this point there are no advanced debug tools to investigate on-device app crashes. However you can use adb application (found under Android-SDK/platform-tools) with logcat parameter. It prints status reports from your device. These reports may include information related to the occurred crash.

If you are sure that the crash you're experiencing happens due to a bug in Unity software, please save the adb logcat output, conduct a repro project and use the bugreporter (Help/Report a bug) to inform us about it. We will get back to you as soon as we can.

Page last updated: 2011-02-24



android-unsupported

Graphics

Scripting

Page last updated: 2012-10-08



android-OBBsupport

Under Player Settings | Publishing Settings you'll find the option to split the application binary (.apk) into expansion files (.apk + .obb).

This mechanism is only necessary when publishing to the Google Play Store, if the application is larger than 50 MB. See http://developer.android.com/guide/google/play/expansion-files.html for further information on APK Expansion Files.

When the Split Application Binary option is enabled the player executable and data will be split up, with a generated .apk (main application binary) consisting only of the executable (Java, Native) code (around 10MB), any and all script / plugin code, and the data for the first scene. Everything else (all additional scenes, resources, streaming assets ...) will be serialized separately to a APK Expansion File (.obb).

The Split Application Binary option is not the only way to split an .apk into .apk/.obb (other options include 3rd party plugins/asset bundles/etc), but it's the only automatic splitting mechanism officially supported.

Downloading of the expansion file (.OBB)

Page last updated: 2013-03-14



Android Player Settings

Player Settings is where you define various parameters (platform specific) for the final game that you will build in Unity. Some of these values for example are used in the Resolution Dialog that launches when you open a standalone game, others are used by XCode when building your game for the iOS devices, so it's important to fill them out correctly.

To see the Player Settings choose Edit->Project Settings->Player from the menu bar.


Global Settings that apply to any project you create.
Cross-Platform Properties
Company NameThe name of your company. This is used to locate the preferences file.
Product NameThe name that will appear on the menu bar when your game is running and is used to locate the preferences file also.
Default IconDefault icon the application will have on every platform (You can override this later for platform specific needs).

Per-Platform Settings

Desktop

Web-Player

Resolution And Presentation

Resolution
Default Screen WidthScreen Width the player will be generated with.
Default Screen HeightScreen Height the plater will be generated with.
Run in backgroundCheck this if you dont want to stop executing your game if the player looses focus.
WebPlayer TemplateFor more information you should check the "Using WebPlayer templates page", note that for each built-in and custom template there will be an icon in this section.

Icon

Icons don't have any meaning for most webplayer builds but they are needed for Native Client builds used as Chrome applications. You can set these icons here.

Other Settings

Rendering
Rendering PathThis property is shared between Standalone and WebPlayer content.
Vertex LitLowest lighting fidelity, no shadows support. Best used on old machines or limited mobile platforms.
Forward with ShadersGood support for lighting features; limited support for shadows.
Deferred LightingBest support for lighting and shadowing features, but requires certain level of hardware support. Best used if you have many realtime lights. Unity Pro only.
Color SpaceThe color space to be used for rendering
GammaSpace RenderingRendering is gamma-corrected
Linear Rendering Hardware SamplingRendering is done in linear space
Static BatchingSet this to use Static batching on your build (Inactive by default in webplayers). Unity Pro only.
Dynamic BatchingSet this to use Dynamic Batching on your build (Activated by default).
Streaming
First Streamed LevelIf you are publishing a Streamed Web Player, this is the index of the first level that will have access to all Resources.Load assets.
Optimization
Optimize Mesh DataRemove any data from meshes that is not required by the material applied to them (tangents, normals, colors, UV).
Debug Unload ModeOutput debugging information regarding Resources.UnloadUnusedAssets.
DisabledDon't output any debug data for UnloadUnusedAssets.
Overview onlyMinimal stats about UnloadUnusedAssets usage.
Full (slow)Output overview stats along with stats for all affected objects. This option can slow down execution due to the amount of data being displayed.

Standalone

Resolution And Presentation

Resolution
Default Screen WidthScreen Width the stand alone game will be using by default.
Default Screen HeightScreen Height the plater will be using by default.
Run in backgroundCheck this if you dont want to stop executing your game if it looses focus.
Standalone Player Options
Default is Full ScreenCheck this if you want to start your game by default in full screen mode.
Capture Single ScreenIf enabled, standalone games in fullscreen mode will not darken the secondary monitor in multi-monitor setups.
DisplayResolution Dialog
DisabledNo resolution dialog will appear when starting the game.
EnabledResolution dialog will always appear when the game is launched.
Hidden by defaultThe resolution player is possible to be opened only if you have pressed the "alt" key when starting the game.
Use Player LogWrite a log file with debugging information. If you plan to submit your application to the Mac App Store you will want to leave this option un-ticked. Ticked is the default.
Mac App Store ValidationEnable receipt validation for the Mac App Store.
Supported Aspect RatiosAspect Ratios selectable in the Resolution Dialog will be monitor-supported resolutions of enabled items from this list.

Icon

Override for StandaloneCheck if you want to assign a custom icon you would like to be used for your standalone game. Different sizes of the icon should fill in the squares below.

Splash Image

Config Dialog BannerAdd your custom splash image that will be displayed when the game is starting.

Other Settings

Rendering
Rendering PathThis property is shared between Standalone and WebPlayer content.
Vertex LitLowest lighting fidelity, no shadows support. Best used on old machines or limited mobile platforms.
Forward with ShadersGood support for lighting features; limited support for shadows.
Deferred LightingBest support for lighting and shadowing features, but requires certain level of hardware support. Best used if you have many realtime lights. Unity Pro only.
Color SpaceThe color space to be used for rendering
GammaSpace RenderingRendering is gamma-corrected
Linear Rendering Hardware SamplingRendering is done in linear space
Static BatchingSet this to use Static batching on your build (Inactive by default in webplayers). Unity Pro only.
Dynamic BatchingSet this to use Dynamic Batching on your build (Activated by default).
Optimization
API Compatibility LevelSee below
.Net 2.0.Net 2.0 libraries. Maximum .net compatibility, biggest file sizes
.Net 2.0 SubsetSubset of full .net compatibility, smaller file sizes
Optimize Mesh DataRemove any data from meshes that is not required by the material applied to them (tangents, normals, colors, UV).
Debug Unload ModeOutput debugging information regarding Resources.UnloadUnusedAssets.
DisabledDon't output any debug data for UnloadUnusedAssets.
Overview onlyMinimal stats about UnloadUnusedAssets usage.
Full (slow)Output overview stats along with stats for all affected objects. This option can slow down execution due to the amount of data being displayed.

API Compatibility Level

You can choose your mono api compatibility level for all targets except the webplayer. Sometimes a 3rd party .net dll will use things that are outside of the .net compatibility level that you would like to use. In order to understand what is going on in such cases, and how to best fix it, get "Reflector" on windows.

  1. Drag the .net assemblies for the api compatilibity level in question into reflector. You can find these in Frameworks/Mono/lib/mono/YOURSUBSET/
  2. Also drag in your 3rd party assembly.
  3. Right click your 3rd party assembly, and select "Analyze".
  4. In the analysis report, inspect the "Depends on" section. Anything that the 3rd party assembly depends on, but is not available in the .net compatibility level of your choice will be highlighted in red there.

iOS

Resolution And Presentation

Resolution
Default Orientation(This setting is shared between iOS and Android devices)
PortraitThe device is in portrait mode, with the device held upright and the home button at the bottom.
Portrait Upside Down (iOS Only)The device is in portrait mode but upside down, with the device held upright and the home button at the top.
Landscape Right (iOS Only)The device is in landscape mode, with the device held upright and the home button on the left side.
Landscape LeftThe device is in landscape mode, with the device held upright and the home button on the right side.
Auto RotationThe screen orientation is automatically set based on the physical device orientation.
Auto Rotation settings
Use Animated AutorotationWhen checked, orientation change is animated. This only applies when Default orientation is set to Auto Rotation.
Allowed Orientations for Auto Rotation
PortraitWhen checked, portrait orientation is allowed. This only applies when Default orientation is set to Auto Rotation.
Portrait Upside DownWhen checked, portrait upside down orientation is allowed. This only applies when Default orientation is set to Auto Rotation.
Landscape RightWhen checked, landscape right (home button on the left side) orientation is allowed. This only applies when Default orientation is set to Auto Rotation.
Landscape LeftWhen checked, landscape left (home button is on the right side) orientation is allowed. This only applies when Default orientation is set to Auto Rotation.
Status Bar
Status Bar HiddenSpecifies whether the status bar is initially hidden when the application launches.
Status Bar StyleSpecifies the style of the status bar as the application launches
Default
Black Translucent
Black Opaque
Use 32-bit Display BufferSpecifies if Display Buffer should be created to hold 32-bit color values (16-bit by default). Use it if you see banding, or need alpha in your ImageEffects, as they will create RTs in same format as Display Buffer.
Show Loading IndicatorOptions for the loading indicator
Don't ShowNo indicator
White LargeIndicator shown large and in white
WhiteIndicator shown at normal size in white
GrayIndicator shown at normal size in gray

Icon

Override for iOSCheck if you want to assign a custom icon you would like to be used for your iPhone/iPad game. Different sizes of the icon should fill in the squares below.
Prerendered iconIf unchecked iOS applies sheen and bevel effects to the application icon.

Splash Image

Mobile Splash Screen (Pro-only feature)Specifies texture which should be used for iOS Splash Screen. Standard Splash Screen size is 320x480.(This is shared between Android and iOS)
High Res. iPhone (Pro-only feature)Specifies texture which should be used for iOS 4th gen device Splash Screen. Splash Screen size is 640x960.
iPad Portrait (Pro-only feature)Specifies texture which should be used as iPad Portrait orientation Splash Screen. Standard Splash Screen size is 768x1024.
High Res iPad Portrait (Pro-only feature)Specifies texture which should be used as iPad Portrait orientation Splash Screen. Standard Splash Screen size is 1536x2048.
iPad Landscape (Pro-only feature)Specifies texture which should be used as iPad Landscape orientation Splash Screen. Standard Splash Screen size is 1024x768.
High Res iPad Landscape (Pro-only feature)Specifies texture which should be used as iPad Portrait orientation Splash Screen. Standard Splash Screen size is 2048x1536.

Other Settings

Rendering
Static BatchingSet this to use Static batching on your build (Activated by default). Pro-only feature.
Dynamic BatchingSet this to use Dynamic Batching on your build (Activated by default).
Identification
Bundle IdentifierThe string used in your provisioning certificate from your Apple Developer Network account(This is shared between iOS and Android)
Bundle VersionSpecifies the build version number of the bundle, which identifies an iteration (released or unreleased) of the bundle. This is a monotonically increased string, comprised of one or more period-separated
Configuration
Target DeviceSpecifies application target device type.
iPhone OnlyApplication is targeted for iPhone devices only.
iPad OnlyApplication is targeted for iPad devices only.
iPhone + iPadApplication is targeted for both iPad and iPhone devices.
Target PlatformSpecifies the target arquitecture you are going to build for.(This setting is shared between iOS and Android Platforms)
armv6 (OpenGL ES1.1)Application is optimized for armv6 chipsets
Universal armv6+armv7 (OpenGL ES1.1+2.0)Application supports both armv6 and armv7 chipsets. Note: increases application distribution size
armv7Application is optimized for armv7 chipsets. 1st-2nd gen. devices are not supported. There might be additional requirements for this build target imposed by Apple App Store. Defaults to OpenGL ES 2.0.
Target ResolutionResolution you want to use on your deployed device.(This setting will not have any effect on devices with maximum resolution of 480x320)
Native (Default Device Resolution)Will use the device's native resolution (that is the physical pixels on the screen).
Standard (Medium or Low Resolution)Use the lowest resolution possible (e.g. 480x320 on an iPhone 4).
HD (Highest available resolution)Use the maximum resolution allowed on the device (e.g. 960x640 on an iPhone 4).
Accelerometer FrequencyHow often the accelerometer is sampled
DisabledAccelerometer is not sampled
15Hz15 samples per second
30Hz30 samples per second
60Hz60 samples per second
100Hz100 samples per second
Override iPod MusicIf selected application will silence user's iPod music. Otherwise user's iPod music will continue playing in the background.
UI Requires Persistent WiFiSpecifies whether the application requires a Wi-Fi connection. iOS maintains the active Wi-Fi connection open while the application is running.
Exit on SuspendSpecifies whether the application should quit when suspended to background on iOS versions that support multitasking.
Optimization
Api Compatibility LevelSpecifies active .NET API profile. See below
.Net 2.0.Net 2.0 libraries. Maximum .net compatibility, biggest file sizes
.Net 2.0 SubsetSubset of full .net compatibility, smaller file sizes
AOT compilation optionsAdditional AOT compiler options.
SDK VersionSpecifies iPhone OS SDK version to use for building in Xcode
iOS 4.0iOS SDK 4.0.
iOS Simulator 4.0iOS Simulator 4.0. Application built for this version of SDK will be able to run only on Simulator from the SDK 4.
iOS 4.1iOS 4.1.
iOS Simulator 4.1iOS Simulator 4.1. Application built for this version of SDK will be able to run only on Simulator from the SDK 4.x.
iOS 4.2iOS 4.2.
iOS Simulator 4.2iOS Simulator 4.2. Application built for this version of SDK will be able to run only on Simulator from the SDK 4.x.
iOS 4.3iOS 4.3.
iOS Simulator 4.3iOS Simulator 4.3. Application built for this version of SDK will be able to run only on Simulator from the SDK 4.x.
iOS 5.0iOS 5.0
iOS Simulator 5.0iOS Simulator 5.0. Application built for this version of SDK will be able to run only on Simulator from the SDK 5.x.
iOS latestLatest available iOS SDK. Available since iOS SDK 4.2. (default value)
iOS Simulator latestLatest available iOS Simulator SDK. Available since iOS SDK 4.2.
UnknowniOS SDK version is not managed by Unity Editor.
Target iOS VersionSpecifies lowest iOS version where final application will able to run
3.0iPhone OS 3.0. (default value)
3.1iPhone OS 3.1.
3.1.2iPhone OS 3.1.2.
3.1.3iPhone OS 3.1.3.
3.2iPhone OS 3.2.
4.0iPhone OS 4.0.
4.1iPhone OS 4.1.
4.2iPhone OS 4.2.
4.3iPhone OS 4.3.
5.0iPhone OS 5.0
UnknowniPhone OS SDK version is not managed by Unity Editor.
Stripping Level (Pro-only feature)Options to strip out scripting features to reduce built player size(This setting is shared between iOS and Android Platforms)
DisabledNo reduction is done.
Strip AssembliesLevel 1 size reduction.
Strip ByteCodeLevel 2 size reduction (includes reductions from Level 1).
Use micro mscorlibLevel 3 size reduction (includes reductions from Levels 1 and 2).
Script Call OptimizationOptionally disable exception handling for a speed boost at runtime
Slow and SafeFull exception handling will occur with some performance impact on the device
Fast but no ExceptionsNo data provided for exceptions on the device, but the game will run faster
Optimize Mesh DataRemove any data from meshes that is not required by the material applied to them (tangents, normals, colors, UV).
Debug Unload ModeOutput debugging information regarding Resources.UnloadUnusedAssets.
DisabledDon't output any debug data for UnloadUnusedAssets.
Overview onlyMinimal stats about UnloadUnusedAssets usage.
Full (slow)Output overview stats along with stats for all affected objects. This option can slow down execution due to the amount of data being displayed.

Note: If you build for example for iPhone OS 3.2, and then select Simulator 3.2 in Xcode you will get a ton of errors. So you MUST be sure to select a proper Target SDK in Unity Editor.

API Compatibility Level

You can choose your mono api compatibility level for all targets except the webplayer. Sometimes a 3rd party .net dll will use things that are outside of the .net compatibility level that you would like to use. In order to understand what is going on in such cases, and how to best fix it, get "Reflector" on windows.

  1. Drag the .net assemblies for the api compatilibity level in question into reflector. You can find these in Frameworks/Mono/lib/mono/YOURSUBSET/
  2. Also drag in your 3rd party assembly.
  3. Right click your 3rd party assembly, and select "Analyze".
  4. In the analysis report, inspect the "Depends on" section. Anything that the 3rd party assembly depends on, but is not available in the .net compatibility level of your choice will be highlighted in red there.

Android

Resolution And Presentation


Resolution and presentation for your Android project builds.
Resolution
Default Orientation(This setting is shared between iOS and Android devices)
PortraitThe device is in portrait mode, with the device held upright and the home button at the bottom.
Portrait Upside DownThe device is in portrait mode but upside down, with the device held upright and the home button at the top (only available with Android OS 2.3 and later).
Landscape RightThe device is in landscape mode, with the device held upright and the home button on the left side (only available with Android OS 2.3 and later).
Landscape LeftThe device is in landscape mode, with the device held upright and the home button on the right side.
Use 32-bit Display BufferSpecifies if Display Buffer should be created to hold 32-bit color values (16-bit by default). Use it if you see banding, or need alpha in your ImageEffects, as they will create RTs in same format as Display Buffer. Not supported on devices running pre-Gingerbread OS (will be forced to 16-bit).
Use 24-bit Depth BufferIf set Depth Buffer will be created to hold (at least) 24-bit depth values. Use it only if you see 'z-fighting' or other artifacts, as it may have performance implications.
 
 
Icon

Different icons that your project will have when built.
Override for AndroidCheck if you want to assign a custom icon you would like to be used for your Android game. Different sizes of the icon should fill in the squares below.
 
 
Splash Image

Splash image that is going to be displayed when your project is launched.
Mobile Splash Screen (Pro-only feature)Specifies texture which should be used by the iOS Splash Screen. Standard Splash Screen size is 320x480.(This is shared between Android and iOS)
Splash ScalingSpecifies how will be the splash image scaling on the device.
 
 
Other Settings
Rendering
Static BatchingSet this to use Static batching on your build (Activated by default). Pro-only feature.
Dynamic BatchingSet this to use Dynamic Batching on your build (Activated by default).
Identification
Bundle IdentifierThe string used in your provisioning certificate from your Apple Developer Network account(This is shared between iOS and Android)
Bundle VersionSpecifies the build version number of the bundle, which identifies an iteration (released or unreleased) of the bundle. This is a monotonically increased string, comprised of one or more period-separated(This is shared between iOS and Android)
Bundle Version CodeAn internal version number. This number is used only to determine whether one version is more recent than another, with higher numbers indicating more recent versions. This is not the version number shown to users; that number is set by the versionName attribute. The value must be set as an integer, such as "100". You can define it however you want, as long as each successive version has a higher number. For example, it could be a build number. Or you could translate a version number in "x.y" format to an integer by encoding the "x" and "y" separately in the lower and upper 16 bits. Or you could simply increase the number by one each time a new version is released.
Configuration
Device FilterSpecifies the target architecture you are going to build for.
ARMv7 onlyApplication optimized for ARMv7 CPU architecture. It will also enable correct Android Market device filtering, thus recommended for publishing to the Android Market (only devices supporting Unity Android will list the application on the Android Market).
ARMv6 with VFPApplication optimized for ARMv6 CPU architecture (requires VFP support). Use runtime detection of hardware capabilities rather than relying on the Android Market filtering mechanism. It means the application when published to the Android Market will be visible also to devices not supporting Unity Android. Obviously this is not recommended, especially for paid applications (though can be combined with other means of filtering instead, like OpenGLES version).
Graphics LevelSelect either ES 1.1 ('fixed function') or ES 2.0 ('shader based') Open GL level. When using the AVD (emulator) only ES 1.x is supported.
Install LocationSpecifies application install location on the device (for detailed information, please refer to http://developer.android.com/guide/appendix/install-location.html).
AutomaticLet OS decide. User will be able to move the app back and forth.
Prefer ExternalInstall app to external storage (SD-Card) if possible. OS does not guarantee that will be possible; if not, the app will be installed to internal memory.
Force InternalForce app to be installed into internal memory. User will be unable to move the app to external storage.
Internet AccessWhen set to Require, will enable networking permissions even if your scripts are not using this. Automatically enabled for development builds.
Write AccessWhen set to External (SDCard), will enable write access to external storage such as the SD-Card. Automatically enabled for development builds.
OptimizationSee below
Api Compatibility LevelSpecifies active .NET API profile
.Net 2.0.Net 2.0 libraries. Maximum .net compatibility, biggest file sizes
.Net 2.0 SubsetSubset of full .net compatibility, smaller file sizes
Stripping Level (Pro-only feature)Options to strip out scripting features to reduce built player size(This setting is shared between iOS and Android Platforms)
DisabledNo reduction is done.
Strip AssembliesLevel 1 size reduction.
Strip ByteCode (iOS only)Level 2 size reduction (includes reductions from Level 1).
Use micro mscorlibLevel 3 size reduction (includes reductions from Levels 1 and 2).
Enable "logcat" profilerEnable this if you want to get feedback from your device while testing your projects. So adb logcat prints logs from the device to the console (only available in development builds).
Optimize Mesh DataRemove any data from meshes that is not required by the material applied to them (tangents, normals, colors, UV).
Debug Unload ModeOutput debugging information regarding Resources.UnloadUnusedAssets.
DisabledDon't output any debug data for UnloadUnusedAssets.
Overview onlyMinimal stats about UnloadUnusedAssets usage.
Full (slow)Output overview stats along with stats for all affected objects. This option can slow down execution due to the amount of data being displayed.

API Compatibility Level

You can choose your mono api compatibility level for all targets except the webplayer. Sometimes a 3rd party .net dll will use things that are outside of the .net compatibility level that you would like to use. In order to understand what is going on in such cases, and how to best fix it, get "Reflector" on windows.

  1. Drag the .net assemblies for the api compatilibity level in question into reflector. You can find these in Frameworks/Mono/lib/mono/YOURSUBSET/
  2. Also drag in your 3rd party assembly.
  3. Right click your 3rd party assembly, and select "Analyze".
  4. In the analysis report, inspect the "Depends on" section. Anything that the 3rd party assembly depends on, but is not available in the .net compatibility level of your choice will be highlighted in red there.
!Publishing Settings

Publishing settings for Android Market
Keystore
Use Existing Keystore / Create New KeystoreUse this to choose whether to create a new Keystore or use an existing one.
Browse KeystoreLets you select an existing Keystore.
Keystore passwordPassword for the Keystore.
Confirm passwordPassword confirmation, only enabled if the Create New Keystore option is chosen.
Key
AliasKey alias
PasswordPassword for key alias

Note that for security reasons, Unity will save neither the keystore password nor the key password.

Split Application BinarySplit application binary into expansion files, for use with Google Play Store if application is larger than 50 MB. When enabled the player executable and data will be split up, with a generated .apk consisting only of the executable (Java and Native) code (~10MB), and the data for the first scene. The application data will be serialized separately to an APK Expansion File (.obb).

Flash

Resolution And Presentation

Resolution
Default Screen WidthScreen Width the player will be generated with.
Default Screen HeightScreen Height the plater will be generated with.

Other Settings

Optimization
StrippingBytecode can optionally be stripped during the build.
Optimize Mesh DataRemove any data from meshes that is not required by the material applied to them (tangents, normals, colors, UV).
Debug Unload ModeOutput debugging information regarding Resources.UnloadUnusedAssets.
DisabledDon't output any debug data for UnloadUnusedAssets.
Overview onlyMinimal stats about UnloadUnusedAssets usage.
Full (slow)Output overview stats along with stats for all affected objects. This option can slow down execution due to the amount of data being displayed.

Details

Desktop

The Player Settings window is where many technical preference defaults are set. See also Quality Settings where the different graphics quality levels can be set up.

Publishing a web player

Default Web Screen Width and Default Web Screen Height determine the size used in the html file. You can modify the size in the html file later.

Default Screen Width and Default Screen Height are used by the Web Player when entering fullscreen mode through the context menu in the Web Player at runtime.

Customizing your Resolution Dialog


The Resolution Dialog, presented to end-users

You have the option of adding a custom banner image to the Screen Resolution Dialog in the Standalone Player. The maximum image size is 432 x 163 pixels. The image will not be scaled up to fit the screen selector. Instead it will be centered and cropped.

Publishing to Mac App Store

Use Player Log enables writing a log file with debugging information. This is useful to find out what happened if there are problems with your game. When publishing games for Apple's Mac App Store, it is recommended to turn this off, because Apple may reject your submission otherwise. See this manual page for further information about log files.

Use Mac App Store Validation enables receipt validation for the Mac App Store. If this is enabled, your game will only run when it contains a valid receipt from the Mac App Store. Use this when submitting games to Apple for publishing on the App Store. This prevents people from running the game on any computer then the one it was purchased on. Note that this feature does not implement any strong copy protection. In particular, any potential crack against one Unity game would work against any other Unity content. For this reason, it is recommended that you implement your own receipt validation code on top of this using Unity's plugin feature. However, since Apple requires plugin validation to initially happen before showing the screen setup dialog, you should still enable this check, or Apple might reject your submission.

iOS

Bundle Identifier

The Bundle Identifier string must match the provisioning profile of the game you are building. The basic structure of the identifier is com.CompanyName.GameName. This structure may vary internationally based on where you live, so always default to the string provided to you by Apple for your Developer Account. Your GameName is set up in your provisioning certificates, that are manageable from the Apple iPhone Developer Center website. Please refer to the Apple iPhone Developer Center website for more information on how this is performed.

Stripping Level (Pro-only)

Most games don't use all necessary dlls. With this option, you can strip out unused parts to reduce the size of the built player on iOS devices. If your game is using classes that would normally be stripped out by the option you currently have selected, you'll be presented with a Debug message when you make a build.

Script Call Optimization

A good development practice on iOS is to never rely on exception handling (either internally or through the use of try/catch blocks). When using the default Slow and Safe option, any exceptions that occur on the device will be caught and a stack trace will be provided. When using the Fast but no Exceptions option, any exceptions that occur will crash the game, and no stack trace will be provided. However, the game will run faster since the processor is not diverting power to handle exceptions. When releasing your game to the world, it's best to publish with the Fast but no Exceptions option.

Android

Bundle Identifier

The Bundle Identifier string is the unique name of your application when published to the Android Market and installed on the device. The basic structure of the identifier is com.CompanyName.GameName, and can be chosen arbitrarily. In Unity this field is shared with the iOS Player Settings for convenience.

Stripping Level (Pro-only)

Most games don't use all the functionality of the provided dlls. With this option, you can strip out unused parts to reduce the size of the built player on Android devices.

Windows Store Apps

Most of these settings are transferred to Package.appxmanifest when creating Visual Studio solution for the first time.

Note: If you build your project on top of the existing one, Unity won't overwrite Package.appxmanifest file if it's already present, that means if you change something in Player Settings be sure to check Package.appxmanifest, if you want Package.appxmanifest to be regenerated, simply delete it, and rebuild your project from Unity.

To read more about App package manifest, please visit http://msdn.microsoft.com/en-us/library/windows/apps/br211474.aspx.

Settings from Packaging, Application UI, Tile, Splash screen, Capabilities directly transfer to settings in Package.appxmanifest file.

Certificate

Every Windows Store App needs a certificate which identifies a developer, Unity will create a default certificate, if you won't provide your own.

Compilation

As you know, Unity uses Mono when compiling script files, and you can use the API located in .NET 3.5. Compilation Overrides allows you to use .NET for Windows Store Apps (also known as .NET Core) in your C# files, the API is available here http://msdn.microsoft.com/en-us/library/windows/apps/br230232.aspx.

When Compilation Overrides is set to Use .NET Core, Unity will compile *.cs (which are not located in Plugins, Standard Assets or Pro Standard Assets) files against .NET Core when building Windows Store Apps project.

Note: You won't be able to test .NET Core API in Unity Editor, because it doesn't have access to .NET Core, so you'll be able to test the API only when running Windows Store App.

Note: You cannot use .NET Core API in JS or Boo scripts.

Here's a simple example how to use .NET Core API in scripts.

	string GetTemporaryFolder()
	{
 #if NETFX_CORE
		return Windows.Storage.ApplicationData.Current.TemporaryFolder.Path;
 #else
		return "LocalFolder";
 #endif
	}

Page last updated: 2013-11-05



android-API

Most features of the Android devices are exposed through the Input and Handheld classes. For cross-platform projects, UNITY_ANDROID is defined for conditionally compiling Android-specific C# code.

For further information, see the Input, Mobile Keyboard, Advanced Unity Mobile Scripting and Using .NET API 2.0 compatibility level pages.

Page last updated: 2013-10-10



Android-Plugins

This page describes Native Code Plugins for Android.

Building a Plugin for Android

To build a plugin for Android, you should first obtain the Android NDK and familiarize yourself with the steps involved in building a shared library.

If you are using C++ (.cpp) to implement the plugin you must ensure the functions are declared with C linkage to avoid name mangling issues.

extern "C" {
  float FooPluginFunction ();
} 

Using Your Plugin from C#

Once built, the shared library should be copied to the Assets->Plugins->Android folder. Unity will then find it by name when you define a function like the following in the C# script:-

[DllImport ("PluginName")]
private static extern float FooPluginFunction (); 

Please note that PluginName should not include the prefix ('lib') nor the extension ('.so') of the filename. You should wrap all native code methods with an additional C# code layer. This code should check Application.platform and call native methods only when the app is running on the actual device; dummy values can be returned from the C# code when running in the Editor. You can also use platform defines to control platform dependent code compilation.

Android Library Projects

You can drop pre-compiled Android library projects into the Assets->Plugins->Android folder. Pre-compiled means all .java files must have been compiled into jar files located in either the bin/ or the libs/ folder of the project.

See Android Library Projects for more details.

Deployment

For cross platform deployment, your project should include plugins for each supported platform (ie, libPlugin.so for Android, Plugin.bundle for Mac and Plugin.dll for Windows). Unity automatically picks the right plugin for the target platform and includes it with the player.

Using Java Plugins

The Android plugin mechanism also allows Java to be used to enable interaction with the Android OS.

Building a Java Plugin for Android

There are several ways to create a Java plugin but the result in each case is that you end up with a .jar file containing the .class files for your plugin. One approach is to download the JDK, then compile your .java files from the command line with javac. This will create .class files which you can then package into a .jar with the jar command line tool. Another option is to use the Eclipse IDE together with the ADT.

Using Your Java Plugin from Native Code

Once you have built your Java plugin (.jar) you should copy it to the Assets->Plugins->Android folder in the Unity project. Unity will package your .class files together with the rest of the Java code and then access the code using the Java Native Interface (JNI). JNI is used both when calling native code from Java and when interacting with Java (or the JavaVM) from native code.

To find your Java code from the native side you need access to the Java VM. Fortunately, that access can be obtained easily by adding a function like this to your C/C++ code:

jint JNI_OnLoad(JavaVM* vm, void* reserved) {
  JNIEnv* jni_env = 0;
  vm->AttachCurrentThread(&jni_env, 0);
} 

This is all that is needed to start using Java from C/C++. It is beyond the scope of this document to explain JNI completely. However, using it usually involves finding the class definition, resolving the constructor (<init>) method and creating a new object instance, as shown in this example:-

jobject createJavaObject(JNIEnv* jni_env) {
  jclass cls_JavaClass = jni_env->FindClass("com/your/java/Class");			// find class definition
  jmethodID mid_JavaClass = jni_env->GetMethodID (cls_JavaClass, "<init>",  "()V");		// find constructor method
  jobject obj_JavaClass = jni_env->NewObject(cls_JavaClass, mid_JavaClass);		// create object instance
  return jni_env->NewGlobalRef(obj_JavaClass);						// return object with a global reference
} 

Using Your Java Plugin with helper classes

AndroidJNIHelper and AndroidJNI can be used to ease some of the pain with raw JNI.

AndroidJavaObject and AndroidJavaClass automate a lot of tasks and also use cacheing to make calls to Java faster. The combination of AndroidJavaObject and AndroidJavaClass builds on top of AndroidJNI and AndroidJNIHelper, but also has a lot of logic in its own right (to handle the automation). These classes also come in a 'static' version to access static members of Java classes.

You can choose whichever approach you prefer, be it raw JNI through AndroidJNI class methods, or AndroidJNIHelper together with AndroidJNI and eventually AndroidJavaObject/AndroidJavaClass for maximum automation and convenience.

UnityEngine.AndroidJNI is a wrapper for the JNI calls available in C (as described above). All methods in this class are static and have a 1:1 mapping to the Java Native Interface. UnityEngine.AndroidJNIHelper provides helper functionality used by the next level, but is exposed as public methods because they may be useful for some special cases.

Instances of UnityEngine.AndroidJavaObject and UnityEngine.AndroidJavaClass have a one-to-one mapping to an instance of java.lang.Object and java.lang.Class (or subclasses thereof) on the Java side, respectively. They essentially provide 3 types of interaction with the Java side:-

The Call is separated into two categories: Call to a 'void' method, and Call to a method with non-void return type. A generic type is used to represent the return type of those methods which return a non-void type. The Get and Set always take a generic type representing the field type.

Example 1

//The comments describe what you would need to do if you were using raw JNI
 AndroidJavaObject jo = new AndroidJavaObject("java.lang.String", "some_string"); 
 // jni.FindClass("java.lang.String"); 
 // jni.GetMethodID(classID, "<init>", "(Ljava/lang/String;)V"); 
 // jni.NewStringUTF("some_string"); 
 // jni.NewObject(classID, methodID, javaString); 
 int hash = jo.Call<int>("hashCode"); 
 // jni.GetMethodID(classID, "hashCode", "()I"); 
 // jni.CallIntMethod(objectID, methodID);

Here, we're creating an instance of java.lang.String, initialized with a string of our choice and retrieving the hash value for that string.

The AndroidJavaObject constructor takes at least one parameter, the name of class for which we want to construct an instance. Any parameters after the class name are for the constructor call on the object, in this case the string "some_string". The subsequent Call to hashCode() returns an 'int' which is why we use that as the generic type parameter to the Call method.

Note: You cannot instantiate a nested Java class using dotted notation. Inner classes must use the $ separator, and it should work in both dotted and slashed format. So android.view.ViewGroup$LayoutParams or android/view/ViewGroup$LayoutParams can be used, where a LayoutParams class is nested in a ViewGroup class.

Example 2

One of the plugin samples above shows how to get the cache directory for the current application. This is how you would do the same thing from C# without any plugins:-

 AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); 
 // jni.FindClass("com.unity3d.player.UnityPlayer"); 
 AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"); 
 // jni.GetStaticFieldID(classID, "Ljava/lang/Object;"); 
 // jni.GetStaticObjectField(classID, fieldID); 
 // jni.FindClass("java.lang.Object"); 

 Debug.Log(jo.Call<AndroidJavaObject>("getCacheDir").Call<string>("getCanonicalPath")); 
 // jni.GetMethodID(classID, "getCacheDir", "()Ljava/io/File;"); // or any baseclass thereof! 
 // jni.CallObjectMethod(objectID, methodID); 
 // jni.FindClass("java.io.File"); 
 // jni.GetMethodID(classID, "getCanonicalPath", "()Ljava/lang/String;"); 
 // jni.CallObjectMethod(objectID, methodID); 
 // jni.GetStringUTFChars(javaString);

In this case, we start with AndroidJavaClass instead of AndroidJavaObject because we want to access a static member of com.unity3d.player.UnityPlayer rather than create a new object (an instance is created automatically by the Android UnityPlayer). Then we access the static field "currentActivity" but this time we use AndroidJavaObject as the generic parameter. This is because the actual field type (android.app.Activity) is a subclass of java.lang.Object, and any non-primitive type must be accessed as AndroidJavaObject. The exceptions to this rule are strings, which can be accessed directly even though they don't represent a primitive type in Java.

After that it is just a matter of traversing the Activity through getCacheDir() to get the File object representing the cache directory, and then calling getCanonicalPath() to get a string representation.

Of course, nowadays you don't need to do that to get the cache directory since Unity provides access to the application's cache and file directory with Application.temporaryCachePath and Application.persistentDataPath.

Example 3

Finally, here is a trick for passing data from Java to script code using UnitySendMessage.

using UnityEngine; 
public class NewBehaviourScript : MonoBehaviour { 

	void Start () { 
		AndroidJNIHelper.debug = true; 
		using (AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { 
			jc.CallStatic("UnitySendMessage", "Main Camera", "JavaMessage", "whoowhoo"); 
		} 
	} 

	void JavaMessage(string message) { 
		Debug.Log("message from java: " + message); 
	}
} 

The Java class com.unity3d.player.UnityPlayer now has a static method UnitySendMessage, equivalent to the iOS UnitySendMessage function on the native side. It can be used in Java to pass data to script code.

Here though, we call it directly from script code, which essentially relays the message on the Java side. This then calls back to the native/Unity code to deliver the message to the object named "Main Camera". This object has a script attached which contains a method called "JavaMessage".

Best practice when using Java plugins with Unity

As this section is mainly aimed at people who don't have comprehensive JNI, Java and Android experience, we assume that the AndroidJavaObject/AndroidJavaClass approach has been used for interacting with Java code from Unity.

The first thing to note is that any operation you perform on an AndroidJavaObject or AndroidJavaClass is computationally expensive (as is the raw JNI approach). It is highly advisable to keep the number of transitions between managed and native/Java code to a minimum, for the sake of performance and also code clarity.

You could have a Java method to do all the actual work and then use AndroidJavaObject / AndroidJavaClass to communicate with that method and get the result. However, it is worth bearing in mind that the JNI helper classes try to cache as much data as possible to improve performance.

//The first time you call a Java function like 
AndroidJavaObject jo = new AndroidJavaObject("java.lang.String", "some_string");  // somewhat expensive
int hash = jo.Call<int>("hashCode");  // first time - expensive
int hash = jo.Call<int>("hashCode");  // second time - not as expensive as we already know the java method and can call it directly

The Mono garbage collector should release all created instances of AndroidJavaObject and AndroidJavaClass after use, but it is advisable to keep them in a using(){} statement to ensure they are deleted as soon as possible. Without this, you cannot be sure when they will be destroyed. If you set AndroidJNIHelper.debug to true, you will see a record of the garbage collector's activity in the debug output.

//Getting the system language with the safe approach
void Start () { 
	using (AndroidJavaClass cls = new AndroidJavaClass("java.util.Locale")) { 
		using(AndroidJavaObject locale = cls.CallStatic<AndroidJavaObject>("getDefault")) { 
			Debug.Log("current lang = " + locale.Call<string>("getDisplayLanguage")); 

		} 
	} 
}

You can also call the .Dispose() method directly to ensure there are no Java objects lingering. The actual C# object might live a bit longer, but will be garbage collected by mono eventually.

Extending the UnityPlayerActivity Java Code

With Unity Android it is possible to extend the standard UnityPlayerActivity class (the primary Java class for the Unity Player on Android, similar to AppController.mm on Unity iOS).

An application can override any and all of the basic interaction between Android OS and Unity Android. You can enable this by creating a new Activity which derives from UnityPlayerActivity (UnityPlayerActivity.java can be found at /Applications/Unity/Unity.app/Contents/PlaybackEngines/AndroidPlayer/src/com/unity3d/player on Mac and usually at C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer\src\com\unity3d\player on Windows).

To do this, first locate the classes.jar shipped with Unity Android. It is found in the installation folder (usually C:\Program Files\Unity\Editor\Data (on Windows) or /Applications/Unity (on Mac)) in a sub-folder called PlaybackEngines/AndroidPlayer/bin. Then add classes.jar to the classpath used to compile the new Activity. The resulting .class file(s) should be compressed into a .jar file and placed in the Assets->Plugins->Android folder. Since the manifest dictates which activity to launch it is also necessary to create a new AndroidManifest.xml. The AndroidManifest.xml file should also be placed in the Assets->Plugins->Android folder.

The new activity could look like the following example, OverrideExample.java:

package com.company.product;

import com.unity3d.player.UnityPlayerActivity;

import android.os.Bundle;
import android.util.Log;

public class OverrideExample extends UnityPlayerActivity {

  protected void onCreate(Bundle savedInstanceState) {

    // call UnityPlayerActivity.onCreate()
    super.onCreate(savedInstanceState);

    // print debug message to logcat
    Log.d("OverrideActivity", "onCreate called!");
  }

  public void onBackPressed()
  {
    // instead of calling UnityPlayerActivity.onBackPressed() we just ignore the back button event
    // super.onBackPressed();
  }
} 

And this is what the corresponding AndroidManifest.xml would look like:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.company.product">
  <application android:icon="@drawable/app_icon" android:label="@string/app_name">
	<activity android:name=".OverrideExample"
			  android:label="@string/app_name"
			  android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
        <intent-filter>
			<action android:name="android.intent.action.MAIN" />
			<category android:name="android.intent.category.LAUNCHER" />
		</intent-filter>
	</activity>
  </application>
</manifest> 

UnityPlayerNativeActivity

It is also possible to create your own subclass of UnityPlayerNativeActivity. This will have much the same effect as subclassing UnityPlayerActivity but with improved input latency. Be aware, though, that NativeActivity was introduced in Gingerbread and does not work with older devices. Since touch/motion events are processed in native code, Java views would normally not see those events. There is, however, a forwarding mechanism in Unity which allows events to be propagated to the DalvikVM. To access this mechanism, you need to modify the manifest file as follows:-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.company.product">
  <application android:icon="@drawable/app_icon" android:label="@string/app_name">
	<activity android:name=".OverrideExampleNative"
			  android:label="@string/app_name"
			  android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
  <meta-data android:name="android.app.lib_name" android:value="unity" />
  <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
        <intent-filter>
			<action android:name="android.intent.action.MAIN" />
			<category android:name="android.intent.category.LAUNCHER" />
		</intent-filter>
	</activity>
  </application>
</manifest> 

Note the ".OverrideExampleNative" attribute in the activity element and the two additional meta-data elements. The first meta-data is an instruction to use the Unity library libunity.so. The second enables events to be passed on to your custom subclass of UnityPlayerNativeActivity.

Examples

Native Plugin Sample

A simple example of the use of a native code plugin can be found here

This sample demonstrates how C code can be invoked from a Unity Android application. The package includes a scene which displays the sum of two values as calculated by the native plugin. Please note that you will need the Android NDK to compile the plugin.

Java Plugin Sample

An example of the use of Java code can be found here

This sample demonstrates how Java code can be used to interact with the Android OS and how C++ creates a bridge between C# and Java. The scene in the package displays a button which when clicked fetches the application cache directory, as defined by the Android OS. Please note that you will need both the JDK and the Android NDK to compile the plugins.

Here is a similar example but based on a prebuilt JNI library to wrap the native code into C#.

Page last updated: 2013-10-10



Android Splash Screen

iOS

Under iOS Basic, a default splash screen will be displayed while your game loads, oriented according to the Default Screen Orientation option in the Player Settings.

Users with an iOS Pro license can use any texture in the project as a splash screen. The size of the texture depends on the target device (320x480 pixels for 1-3rd gen devices, 1024x768 for iPad mini/iPad 1st/2nd gen, 2048x1536 for iPad 3th/4th gen, 640x960 for 4th gen iPhone / iPod devices and 640x1136 for 5th gen devices) and supplied textures will be scaled to fit if necessary. You can set the splash screen textures using the iOS Player Settings.

Android

Under Android Basic, a default splash screen will be displayed while your game loads, oriented according to the Default Screen Orientation option in the Player Settings.

Android Pro users can use any texture in the project as a splash screen. You can set the texture from the Splash Image section of the Android Player Settings. You should also select the Splash scaling method from the following options:-

  • Center (only scale down) will draw your image at its natural size unless it is too large, in which case it will be scaled down to fit.
  • Scale to fit (letter-boxed) will draw your image so that the longer dimension fits the screen size exactly. Empty space around the sides in the shorter dimension will be filled in black.
  • Scale to fill (cropped) will scale your image so that the shorter dimension fits the screen size exactly. The image will be cropped in the longer dimension.

Page last updated: 2013-08-12



bb10-gettingstarted

The Blackberry 10 Add-on for Unity allows you to build games and interactive media applications for Blackberry 10 devices. These devices include the Z10 and Q10 products. (Blackberry Playbook does not currently support Blackberry 10 OS.) To configure Unity to build to your Blackberry 10 device read the Setup page.

Further Reading

Page last updated: 2013-04-07



bb10-setup

To get your first project running on your Blackberry 10 device you will need to follow these steps. Note that you will need an internet connection since Unity needs to communicate with Blackberry servers.

  1. Register with Blackberry: If you are not already registered with Blackberry you must go to https://www.blackberry.com/SignedKeys/codesigning.html and register. You will receive one or two emails with two .csj files as attachments. (Be sure to choose 'For BlackBerry PlayBook apps developed using BlackBerry WebWorks, BlackBerry NDK, or AIR - AND - For BlackBerry 10 apps developed using BlackBerry WebWorks, or the BlackBerry Native Plug-in for Visual Studio.'). These emails may take up to 2 hours to arrive. Part of the registration process involves creating a PIN. You will need this PIN in the next step.
  2. Register Machine: In the Unity editor find Player Settings -> Blackberry -> Publishing and select 'Register'. Fill out the window. Note that the CSJ Pin is the PIN you entered when registering with Blackberry.

    If the log file shows errors, then please check you have entered the correct information. The password you enter (and confirm) can be any password, and is used to control access to the machine settings. (You can use 'Restore' to restore registration from a previous backup if you already have registered in the past. If the particular machine is already registered it should be recognized).
  3. Create a backup: Use the 'Backup' button to create a backup zip file of the registration. If you fail to do this and you ever lose your registration files you will be unable to use that same account in the future.
  4. Create a debug Token: A debug token is required to deploy to any Blackberry devices. In Player Settings->BlackBerry->Publishing Settings find Debug Token. Then select Create.

    Specify where to save the token and specify one or more PIN(s) to use. The PIN can be found on the device under Settings->About->Hardware. Enter the PIN in the text box and then press Add. The PIN is then added to the list of PINs. Next press the Generate Token button. Unity will communicate with the Blackberry servers and then create the bar file.
  5. Enable Development Mode: Make sure the device is in Development mode under Settings -> Security and Privacy -> Development Mode. Take note of the IP address. (This IP address assumes a USB connection between Device and Computer - if you need to use Wifi then you can get the IP from About -> Network. The phone still must be in Development Mode). This IP needs to be filled out in 'Device Address' in the Unity Editor. The 'Device Password' is the same password used to unlock the phone (the phone will force a password set when you enable development mode).
  6. Upload debug Token: You can now upload token to device (but you must fill out device IP/Password first). Once the token has been uploaded to the device you are able to build and run in the usual way.
  7. Launching your game: Use File->Build settings. Switch to the Blackberry platform. Ensure that Build Type is set to Debug and Development build it checked. Then click the Build and Run button. Unity will make the game for you, and deploy it to the device. The game should then start up on the device. You've now built and run your first game on your Blackberry10 device.

Page last updated: 2013-10-09



bb10-details

Player Settings

The Player Settings->Per-Platform Settings->Blackberry->Other Settings provides settings which can be configured for your application.


Blackberry10 Others Settings
SettingDescription
Shared Files 
Camera 
GPS Location 
Device Identication 
Microphone 
Scripting Define Symbols 

Touch

On Blackberry10 Touch events are handled just like other mobile platforms. Note however that the touch area on the Z10 is larger than the screen area. This means the returned finger position can be off the edge of the screen, with values negative, and/or greater than the screen width and/or height. Currently (April '13) touch events are lost if the finger position moves off the top edge of the screen.

Page last updated: 2013-04-25



bb10-plugins

Basic steps

1. Download the Desktop plugin example called 'Simplest Plugin' which you can get from the link below:

http://docs.unity3d.com/Documentation/Images/manual/SimplestPluginExample-4.0.zip

Unzip the SimplestPluginExample and place the unzipped project somewhere accessible on your hard drive.

2. Then Download the BlackBerry native SDK and install it by following the on screen prompts,you can find the appropriate version here: http://developer.blackberry.com/native/downloads/

3. Once you have the SDK installed then you need to locate the file 'bbndk-env_10_2_0_1155.sh' file (or .bat file for windows), this file might have different numbers at the end but that's not a problem.

4. In order to set up the paths needed to build BlackBerry object and shared libraries open a terminal window and navigate to the folder which contains this file. Type the command: source bbndk-env_10_2_0_1155.sh (correct the file numbers where necessary). This will set up the paths needed to build BlackBerry object and shared libraries.

 iMac:Applications unity$ cd bbndk/
 iMac:bbndk unity$ ls
 bbndk-env.sh			install
 bbndk-env_10_1_0_1020.sh	licenses
 host_10_1_0_132			target_10_1_0_1020
 ide
 iMac:bbndk unity$ source bbndk-env_10_1_0_1020.sh
 

5. Open the “Unity Project Plugin” (the project we unzipped earlier) within Unity and create the following directory path within the project panel: Assets/Plugins/BlackBerry/libs.

6. Within a terminal window, navigate to the 'EclipsePlugin' directory within SimplestPluginExample, in this directory there should only be Plugin.cpp

 iMac:SimplestPluginExample unity$ cd EclipsePlugin/
 iMac:EclipsePlugin unity$ ls
 Plugin.cpp		
 

7. Provided you have followed the steps correctly, typing the command: which arm-arm-unknown-nto-qnx8.0.0eabi-g++, shouldn't produce any errors otherwise check you have set the paths up correctly.

8. To create the object file, perform the following command within this terminal directory : arm-unknown-nto-qnx8.0.0eabi-g++ -fPIC -marm -shared -c Plugin.cpp . You should now see the Plugin.o file within EclipsePlugin:

 iMac:SimplestPluginExample unity$ cd EclipsePlugin/
 iMac:EclipsePlugin unity$ ls
 Plugin.cpp	Plugin.o	
 

N.B. It is important that the filename matches the name used in the dll import line from the C# script, which in this case is 'ASimplePlugin'.

9. To create the shared library that the project uses, perform the following command: arm-unknown-nto-qnx8.0.0eabi-g++ -shared -o libASimplePlugin.so Plugin.o . You should now see the libASimplePlugin.so file within EclipsePlugin:

 iMac:SimplestPluginExample unity$ cd EclipsePlugin/
 iMac:EclipsePlugin unity$ ls
 Plugin.cpp	Plugin.o      libASimplePlugin.so	
 

10. Copy and paste the generated libASimplePlugin.so file into our earlier created directory SimplestPluginExample/Unity Project Plugin/Assets/Plugins/BlackBerry/libs, you can also drag the file directly into the Unity editor.

11. Deploy the project to your BlackBerry device (provided the build and player settings have been setup) and then check the log (you can do this by accessing Player Settings and clicking 'Get Log'). It should have print statements from the C# file in the project.

Page last updated: 2013-08-16



bb10-controller

Blackberry 10 supports a variety of bluetooth controllers. The buttons and joysticks they support are mapped to the Input class in the usual manner. For the SteelSeries Free mobile wireless controller the assignment on buttons/axes to KeyCode and axis numbers are shown in the table below.

No.Button NameKeyCodeAxis#Comments
14JoystickButton0N/A 
23JoystickButton1N/A 
31JoystickButton2N/A 
42JoystickButton3N/A 
5Left StickJoystickButton8Axis 1 (X) - Horizontal, Axis 2 (Y) - VerticalRange [-1; 1]
6Right StickJoystickButton9Axis 4 - Horizontal, Axis 5 - VerticalRange [-1; 1]
7DpadN/AAxis 6 - Horizontal, Axis 7 - VerticalSet{-1;0;1}
11AJoystickButton6N/A 
12BJoystickButton7N/A 
13Left BumperJoystickButton4N/A 
14Right BumperJoystickButton5N/A 

Page last updated: 2013-07-17



bb10-debugging

When the game runs on device it will write a log file. This is where your Debug.Log messages will go, together with any asserts, information and error messages from Unity. You can fetch this log from the device from the editor. Use Edit->Project Settings->Player->Publishing Settings->Get Log. The log can be written to the hard drive of your computer. An example log file is:

Set current directory to /accounts/1000/appdata/com.unity.doc.testDev_ProductName5a2477fc
Found path: /accounts/1000/appdata/com.unity.doc.testDev_ProductName5a2477fc/com.unity.doc.testDev_ProductName5a2477fc
Data folder: /accounts/1000/appdata/com.unity.doc.testDev_ProductName5a2477fc/app/native/Data
Loading in pref's!
Mono path[0] = '/accounts/1000/appdata/com.unity.doc.testDev_ProductName5a2477fc/app/native/Data/Managed'
Mono config path = '/accounts/1000/appdata/com.unity.doc.testDev_ProductName5a2477fc/app/native/Data/Managed'
Renderer: Adreno (TM) 225
Vendor:   Qualcomm
Version:  OpenGL ES 2.0 2644020
GL_AMD_compressed_ATC_texture GL_AMD_performance_monitor GL_AMD_program_binary_Z400 GL_EXT_robustness GL_EXT_texture_format_BGRA8888
GL_EXT_texture_type_2_10_10_10_REV GL_NV_fence GL_OES_compressed_ETC1_RGB8_texture GL_OES_depth_texture GL_OES_depth24 GL_OES_EGL_image
GL_OES_EGL_image_external GL_OES_element_index_uint GL_OES_fbo_render_mipmap GL_OES_fragment_precision_high GL_OES_get_program_binary
GL_OES_packed_depth_stencil GL_OES_rgb8_rgba8 GL_OES_standard_derivatives GL_OES_texture_3D GL_OES_texture_float GL_OES_texture_half_float
GL_OES_texture_half_float_linear GL_OES_texture_npot GL_OES_vertex_half_float GL_OES_vertex_type_10_10_10_2 GL_OES_vertex_array_object
GL_QCOM_alpha_test GL_QCOM_binning_control GL_QCOM_driver_control GL_QCOM_perfmon_global_mode GL_QCOM_extended_get GL_QCOM_extended_get2
GL_QCOM_tiled_rendering GL_QCOM_writeonly_rendering GL_AMD_compressed_3DC_texture GL_EXT_sRGB GL_EXT_texture_filter_anisotropic
GL_ANGLE_framebuffer_multisample GL_ANGLE_framebuffer_blit GL_OES_mapbuffer 
Creating OpenGLES2.0 graphics device
Initialize engine version: 4.2.0a1 (20a94a2c4d7f)
Begin MonoManager ReloadAssembly
Platform assembly: /accounts/1000/appdata/com.unity.doc.testDev_ProductName5a2477fc/app/native/Data/Managed/UnityEngine.dll (