Tip of the day

From Unify Community Wiki
Revision as of 07:54, 11 December 2012 by Createdbyx (Talk | contribs)

Jump to: navigation, search


December 2012

  • Tip #44 – Serializing your MonoBehaviors private fields

If you have private fields that are wrapped with a public property but you want the value of those private fields to be saved with your scene you can use the SerializeField attribute.

  • Tip #43 – With Unity 4 MonoBehaviors can now be namespaced

Did you know with the release of Unity 4 MonoBehaviours can now be inside namespaces! Finally we can better organize our codez!

November 2012

  • Tip# 42 – Mouse Cursors

Did you know you can customize the look of the mouse cursor in your game by calling Cursor.SetCursor?

  • Tip #41 - Implicit operators (automatic type casting)

This is not so much a unity specific tip but more of a C# language tip. if you are trying to port or adapt your game code from one platform to another like for example from XNA over to unity implicit operators may come in handy for automatically casting types and making your code much more readable and easier to port.

Link to MSDN Documentation here

Often times we programmers can fall into bad programming habits and we can forget or overlook language and API features that would otherwise make our lives easier. :P

  • Tip #40 - Billboarding

This code snip is for object billboarding. Just drop the script onto the object and it will automatically face the camera.

 public class CameraBillboard : MonoBehaviour
    // the camera the the game object will be bill boarded to.
    public Camera m_Camera;
    // if true the game object will be positioned just in front of the cameras near clip plane
    public bool PositionInFrontOfCamera;
    // the offset to position the object when PositionInFrontOfCamera is true
    public float Offset = 0.001f;
    void Awake()
        // if no camera has been specified just use main camera
        if (m_Camera == null) m_Camera = Camera.main;
    void Update()
        // get forward vector of the camera and normalize it
        var vec = m_Camera.transform.forward;
        // set the position of the game object just inside the cameras near clipping plane so it blocks the camera view
        if (this.PositionInFrontOfCamera) this.transform.position = m_Camera.transform.position + (vec * (m_Camera.nearClipPlane + this.Offset));
        // orient the game object to look at the camera
        this.transform.LookAt(this.transform.position + m_Camera.transform.rotation * Vector3.back, m_Camera.transform.rotation * Vector3.up);
  • Tip #39 – RequireComponent attribute

You can specify the RequireComponent attribute on a class that inherits from MonoBehavior and Unity will add the specified component if it is not already present when you add the script to the game object.

 public class SomeBehaviorScript : MonoBehaviour
  • Tip #38 – Performance Optimizations

The unity docs have a great list of recommended performance optimizations available here.

October 2012

  • Tip #37 – Optimize procedurally generated meshes

If you are generating meshes procedurally via scripting you can optimize that mesh for drawing by using MeshUtility.Optimize.

  • Tip #36 – Specify DEFINE directives for conditional compilation

You can use editor scripts to specify additional DEFINE directives for conditional compilation by using the EditorUserBuildSettings.activeScriptCompilationDefines property.

  • Tip #35 – Unity editor Drag & Drop support

If you need your editor script to support drag and drop functionality you can use the methods provided in the DragAndDrop class.

  • Tip #34 – Detect when editor changes play mode state

If you need to know when the unity editor is changing play mode states you can hook into the EditorApplication.playmodeStateChanged callback.

  • Tip #33 – Play & Pause your game in the editor with scripting

Using EditorApplication.isPlaying & EditorApplication.isPaused you can control when you want to run or pause your game in the unity editor using scripting.

September 2012

  • Tip #32 – Can you hear me now?

Unity provides access to the users microphone via the Microphone class.

  • Tip #31 – Location awareness

Unity provides support for location awareness such as longitude, latitude, and altitude in the LocationService class.

  • Tip #30 – Social Platforms

Unity provides built in support for various social platforms including support for custom implementations through the Social class.

  • Tip #29 – Gyroscopes

If the device supports it you can use the Gyroscope class to get gyroscopic information about the orientation and acceleration of the device.

August 2012

  • Tip #28 – System Information

You can get detailed system information by using the SystemInfo class. SystemInfo provides information on the graphic device hardware, processor count, operating system, device type and more. Very handy for gathering stats/trends on your users hardware specs.

  • Tip #27 – OpenGL Drawing

The Unity API provides access to a OpenGL style graphics for immediate mode drawing in the class called “GL”.

  • Tip #26 - Frustum AABB collisions

You can perform Frustum and AABB collision detection using something similar to the fallowing code ...

        public object[] GetObjects(Vector3 position, float distance, float fov, Vector3 direction)
            var results = new List<GameObject>();
            // search all game objects
            var objects = UnityEngine.Object.FindObjectsOfType(typeof(GameObject));
            if (this.camera == null)
                this.cameraGameObject = new GameObject();
                this.camera = this.cameraGameObject.AddComponent<Camera>();
            this.cameraGameObject.transform.position = position;
            this.cameraGameObject.transform.forward = direction;
            this.camera.fov = fov;
            this.camera.far = distance;
            var planes = GeometryUtility.CalculateFrustumPlanes(this.camera);
            foreach (GameObject obj in objects)
                if (obj == this.cameraGameObject)
                // if no collider just ignore
                if (obj.collider == null)
                if (GeometryUtility.TestPlanesAABB(planes, obj.collider.bounds))
            return results.ToArray();
  • Tip #25 – Get/Set caret position for TextArea/TextField object

You can get access to more powerful controls by using an undocumented unity api the TextEditor control.

 var te = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl);
 if (te != null) 
     te.MoveCursorToPosition(new Vector2(5555, 5555));

July 2012

  • Tip #24 – Conditional Compilation

If you need to know what symbols Unity uses for conditional compilation check out the docs page Platform Dependent Compilation

  • Tip #23 – Call JavaScript functions from web player

You can use Application.ExternalCall to call JavaScript functions on the page the web player is displayed in.

  • Tip #22 – Command line arguments

Did you know you can pass in command line arguments when running Unity as well as with the standalone players! Read Here.

  • Tip #21 – Detailed Logs

If you need to get more detailed logging information check out the Log Files page.

  • Tip #20 - Importing Animations using multiple model files

If you have a modal with animation(s) you can export the model without any animation. Then export additional copies of the model with animation and with the same name but with @animationname at the end of the file name. Read the section on “Importing Animations using multiple model files” here.

  • Tip #19 – Determine platform

If you need to know what platform your code is running under you can use Application.platform.

  • Tip #18 - Running Editor Script Code on Launch

If you need to run some script code as soon as the editor has launched you can use the InitializeOnLoad attribute.

  • Tip #17 - MenuItem shortcut keys

With scripting you can add menu items that have shortcut keys assigned to them. Read the MenuItem description for more information.

  • Tip #16 - Gizmos

A great way to help debug your game is to use Gizmos to visually represent empty game objects in your scene. BurgZergArcade example

  • Tip #15 - Tags

When working with multiple duplicate game objects you may want use tags to uniquely identify a specific object. You can then use GameObject.FindGameObjectsWithTag to select that specific object in your scripts.

  • Tip #14 - Unity Console Output

If you need to output information to the unity console check out the Debug class.

June 2012

  • Tip #13 - Screen Resolution

If you need to set the screen resolution of your game via scripting check out Screen.SetResolution.

  • Tip #12 - Collider manipulation

Did you know that you can manipulate a game objects collider in the scene view by holding down the 'Shift' key. Holding shift will display the colliders control dots. Just drag the dots to adjust the collider!

  • Tip #11 - Snap to vertex

Hold the 'V' key while the translate tool is active and you can drag an object by it's vertices and snap that vertex to another objects vertex!

  • Tip #10 - Inspector lock

The inspector window contains a small lock icon in the top right of the window. If you select a game object and click the lock the inspector will be locked to that object and will not change when you select other objects. Click again to disable the lock. This allows you to have multiple inspector windows open with locks to different objects.

  • Tip #9 - Adding Undo support to custom editor scripts

To allow the user to undo actions that are performed by a custom editor script you can use Undo.RegisterUndo.

    foreach (var item in Selection.transforms)
        Undo.RegisterUndo(item, "Move " + item.name);
        var pos = item.position;
        pos = new Vector3(activeObject.transform.position.x, pos.y, pos.z);
        item.transform.position = pos;
  • Tip #8 - Execute menu items from editor script

If you want to take advantage of functionality that is provided by menu commands you can use EditorApplication.ExecuteMenuItem in your editor scripts to execute them.

  • Tip #7 - Hide/show objects in the hierarchy window

Are you working on a large project but dislike how many objects you have to weed through in the hierarchy window? You can create editor scripts that change the objects Object.hideFlags property to hide or show the object in the hierarchy window.

    var item = Selection.activeGameObject;
    if ((item.hideFlags & HideFlags.HideInHierarchy) == HideFlags.HideInHierarchy)
        item.hideFlags = item.hideFlags ^ HideFlags.HideInHierarchy;
        item.active = !item.active;
        item.active = !item.active;

Notice that item.active = !item.active is specified twice. Currently in unity 3.5 you need those 2 lines of code for the game object to hide and show properly in the hierarchy window.

NOTICE: GameObject.active is obsolete use GameObject.SetActive instead

  • Tip #6 - Saving editor/player settings across sessions

Wondering how to save player preferences across sessions or save settings for an editor script to use? Check out EditorPrefs & PlayerPrefs.

  • Tip #5 - Custom Preferences Window settings

If you are writing custom editors for unity and you need to have a way of editing the tools settings you can have those settings show up in the Unity Preferences Window "Edit -> Preferences...".

Just create a new editor script that has a public class and add the fallowing lines of code ...

    // Add preferences section named "cbxTools" to the Preferences Window
    public static void PreferencesGUI()
        // Preferences GUI


  • Tip #4 - Draw editor gui's only in active scene view

If you are creating custom editors for unity but only want the gui for that editor to be drawn in the currently active scene view try this ...

    if (SceneView.mouseOverWindow.GetInstanceID() == SceneView.currentDrawingSceneView.GetInstanceID())

May 2012

  • Tip #3 - Infinite Recursion / Stack Overflow

If your suddenly finding that Unity will instantly terminate while running your code, check if you are invoking any infinite recursion loops. Unity tends to terminate instantly if this occurs in your code.

  • Tip #2 - Game object Icons

You can visually tag your game objects with icons by selecting the object and clicking the Red/Green/Blue colored cube in the upper left of the inspector window.


You can select a colored Label, Dot, or a Texture from your assets.

  • Tip #1 - Prevent config dialog from showing when running your compiled game

When you building your standalone unity game using "File -> Build & Run" and then run the *.exe that was generated you will see a dialog pop up.

To prevent the configuration window from being shown select "File -> Build Settings..." in unity and click the "Player Settings" button at the bottom of the window. The Unity inspector window will contain a number of options. Find the drop down titled "Display Resolution Dialog" and set it to "Disabled". Rebuild your game and run the generated *.exe. No more dialog pop up!

Older Tips

  • When move a GameObject, hold the Key V,will fast align.
  • A skinned character updates its vertices every frame, even when not animating. To freeze a skinned character in place without making it disappear or revert to a T-pose, set its SkinnedMeshRenderer.bones field to null.
  • There are two really nice hotkeys to insert or delete array elements in the inspector. SHIFT + DEL will delete the selected element and CTRL + D will duplicate it. SHIFT is only needed for reference types like GameObject[].
  • If you are dealing with deep hierarchies you can hold down the ALT button when toggling expansion of an item, to recursively toggle the tree.
  • When you're using Debug.Log or related methods, provide the instance of the script so you can click the log output and have the relevant object selected in editor! Debug.Log("Test", this);
  • If you're placing objects in the screen and want them to "snap" into place (great for placing items on the ground) you can hold the Command key (Control on Windows) while dragging the object's axis (snap increments are defined in Edit->Snap Settings)
  • Importing classes in JavaScript. Tired of writing Debug.Log and SendMessageOptions.DontRequireReceiver? Did you know that static members of classess and enums can be imported just like importing namespaces. Simply add import UnityEngine.Debug; and import UnityEngine.SendMessageOptions and then you can write Log("my log string") and SendMessage("ApplyDamage",2.0,DontRequireReceiver);.
  • Deleting objects. Use Command + Backspace in the Scene, Hierarchy and Project views to remove objects. In the Scene and Hierarchy views this will just remove the selected instance of the object. In the Project view this will remove the selected object file and put it in your system Trash.
  • If you need some textures, like font textures, to not be affected by Texture.masterTextureLimit, disable Generate Mip Maps in the texture's import settings. On the down side, this can adversely affect clarity of rendering at smaller scales.
  • Boo has some handy built-in functions like shell(), join() and reversed(). And the cool part? They are available from JavaScript as well.
  • Every built-in component in the inspector has a small question mark in the right of it's heading. That's the quickest way to open the context-help for that component. It's your friend.
  • To remember which color means what on an axis in Unity, just remember the mnemonic: RGB = XYZ.
  • You can use keyboard shortcuts for Edit->Load Selection and Edit->Save Selection to speed up the selection of commonly used parts in your scene.
  • If you option-click an object in your hierarchy, the entire hierarchy within it will expand and unexpand.
  • You can write Editor scripts to greatly reduce project-specific tedium when making something with Unity. These are just as easy to write as regular scripts, and can save you a lot of hassle. See the Wizard Archive for some examples.
  • If you have the problem when importing models that Vector3.up points in the wrong direction (or for any of the other directions), make the game model in question the child of a blank game object, and orient it correctly in local space.
  • When assigning properties of components in the Inspector, you can click on the triangle to pop up a menu of choices. Type in the name of the thing you want and press enter to assign it. This can be a speedy alternative to using drag-and-drop.
  • When entering text in the Inspector view, you can press option-return to get a new line. This is useful for writing multiline things with GUIText objects.
  • If you only have one editor view and no game views in the Unity pane set up, the editor view will be automatically replaced with a game view when you enter play mode and back again when you press stop. This is a nice feature when you are working on a small monitor.
  • Use Tags to assign your own categories and attributes to game objects. Then scripts can refer to the tags. Example: if (contact.otherCollider.tag == "Enemy") or GameObject.FindWithTag ("Enemy")
  • If you want to move a file inside of a project use Unity's project view to move it and not the Finder. This way all references and import settings of the file will be maintained.

Note: Place your new tip at the top of the list, not at the bottom.

Personal tools