Tip of the day

May 2014

 *  Tip #73 – GUI Matrix 

Did you know that the GUI class has a matrix property that you can use to rotate and scale your gui elements.

The sample behaviour that is provided below will scale and rotate a gui label in the center of the screen.

August 2013

 *  Tip #72 - PropertyDrawer 

Ever wish you could draw properties for serializable classes and script variables using your own gui logic? Unity 4 introduces the PropertyDrawer base class to do just that!


 *  Tip #71 – Right click “Create unity project” 

Not a unity specific tip but still a handy unity helper for creating a unity project from file explorer. *Works only for windows platforms.* Download the CreateUnityProject.reg file below or open up Notepad and paste the snippet below then save the file with a *.reg file extension. Next navigate to the file and right click on it and select “Merge” from the popup menu. You should now be able to create a new unity project by right clicking on a empty folder in File Explorer and selecting “Create unity project”.

CreateUnityProject.reg



Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\Folder\shell\Create unity project] [HKEY_CLASSES_ROOT\Folder\shell\Create unity project\command] @="\"C:\\Program Files (x86)\\Unity\\Editor\\unity.exe\" -createProject \"%1\""

July 2013

 *  Tip #70 – 50 Tips in one! 

I came across this article while searching for a way of unit testing my unity GUI windows. A link to the article is available here 50 Tips for Working with Unity (Best Practices). It contains some very sound advice and is well worth the time to read through.


 *  Tip #69 – Let it shine! 

Seems like a no brainer but setting up a empty prefab with one or more lights in it can allow you to quickly light up your test scene quick and easy with predictable results. It also helps when you want to keep the same consistent lighting modal from scene to scene. Simply change the lighting in the prefab and hit apply to update all scenes that use it.
 *  Tip #68 – Show Notification 

Ever wonder how some unity extensions show a notification overlay? Check out the EditorWindow.ShowNotification method.



You can get access to the build order for scenes in your editor scripts by calling EditorBuildSettings.scenes. This allows you to control what scenes are included with the build through your editor code.
 *  Tip #67 – Get and set build order of scenes 



May 2013
Need to send simulated user input to the game window? Unity provides the EditorGUIUtility.QueueGameViewInputEvent method for doing just that. Using this method you could construct a utility that captures and plays back user input as your game is running which would be handy for debugging and unit testing purposes.
 *  Tip #66 - QueueGameViewInputEvent 


 *  Tip #65 – Get asset path of UnityEngine.Object 

Below is a simple bit of code that will attempt to retrieve the asset path of the prefab stored on disk. The method will also try to walk up the prefab hierarchy if the prefab parameter appears to be a instance of the original.

April 2013

 *  Tip #64 – Detect when unity compiles scripts 

If you have some editor scripts and you want to detect weather or not unity has compiled your scripts you can try this simple method.

Created a private class within your editor window and declare a field of that private class.

In the OnGUI method (or where appropriate) perform a check to see if the field is null. If it’s null you can assume that unity compiled your scripts again so do what you need to do is create a new instance of the private class and assign it to the field.

The next time unity re-compiles your scripts the field will loose it’s reference and will be null again.

Not a unity specific tip but still a handy unity helper for opening a unity project from file explorer. *Works only for windows platforms.* Download the OpenInUnity.reg file below or open up Notepad and paste the snippet below then save the file with a *.reg file extension. Next navigate to the file and right click on it and select “Merge” from the popup menu. You should now be able to open a unity project folder by right clicking on it in File Explorer and selecting “Open with Unity”.
 *  Tip #63 – Right click “Open with Unity” 

(Contains OpenInUnity.reg file)



Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Folder\shell\Open with Unity\command] @="\"C:\\Program Files (x86)\\Unity\\Editor\\unity.exe\" -projectPath \"%1\""

Unity comes with a helper method for generating a unique asset paths called AssetDatabase.GenerateUniqueAssetPath. The documentation for this method is rather minimal but the code example below should help you understand how to use it a little better.
 *  Tip #62 - Generate Unique Asset Path 



Below is a code sample containing drawing methods for drawing check boxes or any control type in a grid based layout similar to the SelectionGrid.
 *  Tip #61 – DrawGenericGrid & DrawCheckBoxGrid 

Here is a simple example of how to use the draw methods



You can set the mouse cursor for a UI control by using EditorGUIUtility.AddCursorRect and specifying a MouseCursor enum.
 *  Tip #60 – Set mouse cursor for unity UI control 

March 2013
Ever wonder how unity makes assets in the project window pop out when you select a link to them in the inspector? See the EditorGUIUtility.PingObject method.
 *  Tip #59 – PingObject 



If you are writing UI code and you want the controls you are drawing to appear as if they are labels until they are in focus you can use the EditorGUIUtility.LookLikeInspector & EditorGUIUtility.LookLikeControls methods.
 *  Tip #58 – LookLikeControls & LookLikeInspector 

I recently came across a strange behavior while loading text resource assets. In particular the Resources.LoadAll method does not accept Path.DirectorySeparatorChar characters in a path. In fact it only accepts Path.AltDirectorySeparatorChar characters. This behavior is different then standard .net file/folder methods that accept either Path.AltDirectorySeparatorChar or Path.DirectorySeparatorChar without distinction. What this means is that you can’t directly use Path.Combine to build a path and pass it to the Resources.LoadAll method you first have to replace any Path.DirectorySeparatorChar characters with Path.AltDirectorySeparatorChar characters.
 *  Tip #57 – Resource.Load/LoadAll Gotchas 

The documentation for Resources.Load also does not mention this behavior.

I have submitted a bug report here.

Febuary 2013
There is no Unity specific API for getting the project folder, but you can use System.IO.Directory.GetCurrentDirectory. The unity editor expects the current folder to be set to the project folder at all times.
 *  Tip #56 – Get project folder & current directory 

If you are changing the current directory in your editor scripts using System.IO.Directory.SetCurrentDirectory you need to restore the directory back to the project folder when you are done. Otherwise the next time unity compiles your scripts it will prompt you with a dialog box and a message stating you need to restore the current directory back to the project directory and only gives you a “Quit” button to click on that will quit unity.

I’ve recently come across what initially seems like a bug with the Unity 4 editor. it involves the use of the Resources.Load method from within a class marked InitializeOnLoad.
 *  Tip #55 – InitializeOnLoad & Resources.Load gotcha’s 

Take the fallowing example code … After Unity compiles the scripts it will invoke any static constructors of classes marked with InitializeOnLoad. But at this point I suspect that Unity has not yet identified assets you have within any Resources folders. When the class constructor calls the Resources.Load method it will fail to read the test.txt resource file and return a warning message out to the console.

What you could do at this point is right click the “Assets” folder in the project window and select “Reimport”. Unity will reimport the assets and again call classes marked with InitializeOnLoad. But this time Resources.load will successfully load the test.txt file resource and display it’s contents out to the Unity console window.

One work around to this is to hook into the EditorApplication.update callback and make a call to the LoadData method from there. An example is provided below … Again I am unsure whether this is an actual bug or not but I have submitted a Unity bug report anyway just in case. Here is a link to the my [bug report]

The code below allows you to scale a GameObject transform to a specific size along the x & z axis by taking into account the GameObjects renderer bounds if a renderer component is attached.
 *  Tip #54 – ScaleTransform 

Using the Undo.IncrementCurrentEventIndex allows your editor scripts to undo a single action rather then have unity undo many actions that may have occurred in rapid succession. Place the code below into a “Editor” folder for it to run.
 *  Tip #53 – Undo.IncrementCurrentEventIndex 

The “create object” button will create 10 cubes and call Undo.RegisterCreatedObjectUndo for each of them. Click this button then press ctrl+z to undo all of the objects that were created.

The second button “create single object” will also create 10 cubes but will also call the Undo.IncrementCurrentEventIndex method notifying unity that each object that is created should have a separate undo action. Click “create single object” to create 10 cubes then press ctrl+z to undo each object creation individually.

NOTE: At the time of this writing the unity documentation does not have information on the Undo.IncrementCurrentEventIndex method and searching for it also comes back with zero results.

If you are submitting packages to the asset store and are including version changes that contain html links, remember to specify target="_blank" in your link attributes. Failure to do so can result in the asset store window being replaced by the web page that your link was pointing to. In some occasions it can also cause unity to crash.
 *  Tip #52 – Providing proper links in version changes 



I have been thinking that because texture atlases are so common Unity should have some build in support for generating them. Turns out it already does! Check out the Texture2D.PackTextures method.
 *  Tip #51 – Texture Atlas support 

If your Unity code requires conditional compilation symbols to be present this bit of code may come in handy. After unity compiles your scripts it executes any classes that have the InitializeOnLoad attribute. You can call the SetupConditionalCompilation method provided in the code snippet below to ensure that the conditional compilation symbols persist in your unity project. If a symbol was not present and was added it will write out a notification in the unity console.
 *  Tip #50 – Ensure conditional compilation symbols are present 

January 2013
Here is a C# script for visualizing render bounds. Just attach it to a game object and it will draw the render bounds of the game object and all it’s children. Handy for debugging!
 *  Tip #49 – Visualizing Render Bounds 

And also the code for the GetBoundsWithChildren method.

Recently I needed to force the inspector to redraw itself from a piece of code outside of a Editor class. The solution I came up with was to call SetDirty on all selected objects of the type I was interested in. The inspector then picked up on the change and refreshed itself immediately. Although this code works under Unity 4 it is a hack and there may be a better way to force the inspector to redraw itself.
 *  Tip #48 – Refresh Inspector 

Archived Years

 * Tip of the day entries for 2012

Older Tips
Note: Place your new tip at the top of the list, not at the bottom.
 * 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[].
 * 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.