Website may be up and down over next few months. I'm currently doing a complete overhaul of everything. Going back to simple individual .htm pages, new overall site theme, sanitizing and cleaning up html of all pages and blog posts, attempting to implement a new tooling and publishing system etc etc.

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.

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.

    using UnityEngine;
    using UnityEditor;

    public class UndoTest : EditorWindow
    {

        public void OnGUI()
        {
            if (GUILayout.Button("create object"))
            {
                this.Create(false);
            }
            if (GUILayout.Button("create single object"))
            {
                this.Create(true);
            }

            GUILayout.Label("use ctrl+z to undo each action");
        }

        private void Create(bool single)
        {
            for (int i = 0; i < 10; i++)
            {
                if (single)
                {
                    Undo.IncrementCurrentEventIndex();
                }

                var obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
                obj.transform.position = new Vector3(Random.Range(-10, 10), Random.Range(-10, 10), Random.Range(-10, 10));

                Undo.RegisterCreatedObjectUndo(obj, "create " + obj.name);
            }
        }

        [MenuItem("CBX/UndoTest")]
        public static void ShowWindow()
        {
            GetWindow<UndoTest>("UndoTest").Show();
        }
    }

/// <summary>
/// Packs color components into a <see cref="uint"/> type.
/// </summary>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
/// <param name="a">The alpha component.</param>
/// <returns>Returns a uint representing the color.</returns>
public static uint Pack(int r, int g, int b, int a)
{
    return (((uint)r & 0xff)) | (((uint)g & 0xff) << 8) | (((uint)b & 0xff) << 16) | (((uint)a & 0xff) << 24);
}

/// <summary>
/// Unpacks a <see cref="uint"/> type into a color type.
/// </summary>
/// <param name="value">The packed color value to unpack.</param>
/// <returns>Returns a color type from the unpacked values.</returns>
public static Color Unpack(uint value)
{
    var r = (byte)(value);
    var g = (byte)(value >> 8);
    var b = (byte)(value >> 16);
    var a = (byte)(value >> 24);

    return new Color(r, g, b, a);
}

Today I was writing some C# code where I needed to manage a multidimensional array. Specifically I needed to store a items using Column, Row, & Depth as indexers. Instead I wrote a Array3D class that used generics to store any type and internally it uses a single dimensional array and a little bit of math to select the right index.

Not long after I started writing it Déjà vu set in. You know I could have swore I’ve written this class some time ago. Searching through hundreds of projects and tens of thousands of files dating back to 2001 ala .NET 1.0 I came up with nothing. I even went a little nuts and searched back further into my old Turbo Pascal and QBasic code but still found nothing.

Google, DuckDuckGo, & Bing searches were no help either. I could not shake the feeling I have written or have come across this code before. Maybe not in C# but in some other language. I’m sure I have …

This is not the first time I have started to write code and had a strong sense that I have written this code before as I’m sure many programmers do. Maybe it’s just me but with all our modern fancy IDE’s and add-ons archiving code for long periods of time, as in decades, does not seem to be something that has been readily addressed. If there is one thing I absolutely hate is having to repeat my self to the computer when it comes to coding. it’s also why I have visual studio set to auto save every 60 seconds.

Also hard to believe .NET is pushing 12+ years already. Hard to believe that the so called high tech industry essentially has not changed at all since the early 1960’s. Yes, 1960’s & 70’s that’s the era when the first high level languages were originally developed. And here we are 50+ years later and were still just an endless sea of primates spanking our hands on the keyboard just hoping for the best. But that is a rant for another time. :P

So to try and address the issue of code loss I have decided to start a “Code Snippets” series to archive various code snippets in an effort to make searching for them a little bit easier.


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.

var objects = Selection.GetFiltered(typeof(GridMap), SelectionMode.TopLevel);
foreach (var o in objects)
{
    EditorUtility.SetDirty(o);
}

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


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.


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.


I have made a few minor changes to my Tile material Creation Window.

  • Provided a download link to the second release of the tool.
  • Added inset field to tweak the selection rectangle by a small amount to help clip off any unwanted pixels bleeding over from adjacent tiles.
  • Fixed a small bug where selection rectangles were not being drawn exactly where they should be

I have created a tool to assit in creating materials from tiles in a tile set. See the Tile Material Creation Window page for *.unitypackage download and more information.


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.


Created by: X

Just another personal website in this crazy online world

Name of author Dean Lunz (aka Created by: X)
Computer programming nerd, and tech geek.
About Me -- Resume