Editor script - selecting object for rename

I’ve adapted an example Editor script to create an empty game object childed under the currently selected object. It works great but every time I use it I have to manually select the new object to rename it. It seems like there should be an automatic way to do this - so I can just start typing the name after I hit the hotkey to run the script.

// JavaScript example:
// Add menu named "Do Something" to the main menu
@MenuItem ("GameObject/Empty Child")
static function DoSomething ()
{
//Debug.Log ("Perform operation");
	var empty = GameObject();
	empty.transform.parent = Selection.activeTransform;
	empty.transform.localPosition = Vector3.zero;
	empty.transform.localRotation = Quaternion.identity;
	empty.name = "_";
	Selection.activeTransform = empty.transform;
}

// Validate the menu item.
// The item will be disabled if no transform is selected.
@MenuItem ("GameObject/Empty Child", true)

static function ValidateDoSomething () {
	return Selection.activeTransform != null;
}

I don’t think there is any editor function to activate the editing mode on an object’s name.

using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

namespace Tweeazy.Editor {
    internal class MenuItems : AssetPostprocessor {
        private static string _createdAssetPath;

        [MenuItem("Assets/Create/Tweeazy/Animation")]
        internal static void CreateAsset() {

            _createdAssetPath = "Assets/Text.text";

            File.WriteAllText(_createdAssetPath, "[]");

            AssetDatabase.Refresh();
        }

        private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets,
            string[] movedAssets,
            string[] movedFromAssetPaths) {
            if (string.IsNullOrEmpty(_createdAssetPath)) {
                return;
            }

            EditorApplication.delayCall += RenameAsset;
        }

        private static void RenameAsset() {
            Selection.activeObject = AssetDatabase.LoadAssetAtPath(_createdAssetPath, typeof(UnityEngine.Object));
            EditorApplication.delayCall += () => {
#if UNITY_EDITOR_WIN
    EditorWindow.focusedWindow.SendEvent(new Event { keyCode = KeyCode.F2, type = EventType.KeyDown });
#elif UNITY_EDITOR_OSX
                EditorWindow.focusedWindow.SendEvent(new Event { keyCode = KeyCode.Return, type = EventType.KeyDown });
#endif
                _createdAssetPath = null;
            };
        }
    }
}
2 Likes

You are a hero. Thank you