Tip of the day entries for 2013

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