Tip of the day entries for 2012

From Unify Community Wiki
Jump to: navigation, search

Contents

December 2012

  • Tip #47 - AssetPreview

Did you know your editor scripts can acquire a preview texture for an asset? Check out the members of the AssetPreview class.

  • Tip #46 – ExecuteInEditMode attribute

if you have MonoBehavior code that you want to run while in the unity editor you can use the ExecuteInEditMode attribute and your mono behavior will run as though it was in play mode.

  • Tip #45 – DrawGizmo attribute

The DrawGizmo attribute allows you to setup your gizmo drawing code some place other then with your MonoBehavior class. The code below shows an example of the DrawGizmo attribute used on a method within a Editor class.

    /// <summary>
    /// Provides a editor for the <see cref="TileMap"/> component
    /// </summary>
    [CustomEditor(typeof(TileMap))]
    public class TileMapEditor : Editor
    {
        /// The RenderMapGizmo method will be called if the map is selected. 
        [DrawGizmo(GizmoType.Selected | GizmoType.Active)]
        static void RenderMapGizmo(TileMap map, GizmoType gizmoType)
        {
            // store map width, height and position
            var mapWidth = map.Columns * map.CellWidth;
            var mapHeight = map.Rows * map.CellHeight;
            var position = map.transform.position;
            var activelayerHeight = map.ActiveLayer * map.Depth;
 
            if (map.drawGridLines)
            {
                // draw layer border
                Gizmos.color = Color.white;
                Gizmos.DrawLine(
                    position + new Vector3(0, activelayerHeight, 0), position + new Vector3(mapWidth, activelayerHeight, 0));
                Gizmos.DrawLine(
                    position + new Vector3(0, activelayerHeight, 0), position + new Vector3(0, activelayerHeight, mapHeight));
                Gizmos.DrawLine(
                    position + new Vector3(mapWidth, activelayerHeight, 0),
                    position + new Vector3(mapWidth, activelayerHeight, mapHeight));
                Gizmos.DrawLine(
                    position + new Vector3(0, activelayerHeight, mapHeight),
                    position + new Vector3(mapWidth, activelayerHeight, mapHeight));
 
                // more draw logic here
        }
    }

The alternative is that you can have a method in your MonoBehavior called OnDrawGizmosSelected

    /// <summary>
    /// Provides a component for tile mapping.
    /// </summary>
    public class TileMap : MonoBehaviour
    {
 
        /// <summary>
        /// When the game object is selected this will draw the gizmos
        /// </summary>
        /// <remarks>Only called when in the Unity editor.</remarks>
        private void OnDrawGizmosSelected()
        {
            // gizmo draw code goes here            
        }
    }

… But since gizmo drawing logic is typically for use within the unity editor the DrawGizmo attribute allows you to place the draw logic in a more appropriate location.

  • 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;
        vec.Normalize();
 
        // 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.

 [RequireComponent(typeof(RigidBody))]
 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)
                {
                    continue;
                }
 
                // if no collider just ignore
                if (obj.collider == null)
                {
                    continue;
                }
 
                if (GeometryUtility.TestPlanesAABB(planes, obj.collider.bounds))
                {
                    results.Add(obj);
                }
            }
 
            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
    [PreferenceItem("cbxTools")]
    public static void PreferencesGUI()
    {
        // Preferences GUI
        cbxToolPreferencesConfig.Instance.DrawGUI();
    }

CustomPreferences.png

  • 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())
    {
        this.DrawGUI(SceneView.currentDrawingSceneView);
    }

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.

UnityIcons.png

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!

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Tools