Hi all,
I have an editor script that clones an existing GameObject then selects it in the hierarchy. I want to rename the GameObject immediately after selection, mimicing the F2 rename feature.
Any way to do this in code?
Thanks.
Oribow
2
The script posted in the old answer no longer works in newer unity versions. Use this instead:
using UnityEngine;
using UnityEditor;
using System.Reflection;
public class ObjClone : EditorWindow
{
// Add menu named "My Window" to the Window menu
[MenuItem("Window/ObjClone")]
static void Init()
{
// Get existing open window or if none, make a new one:
ObjClone window = (ObjClone)EditorWindow.GetWindow(typeof(ObjClone));
window.Show();
}
GameObject g;
GameObject clone;
volatile bool triggerRename;
private static double renameTime;
void OnGUI()
{
g = (GameObject)EditorGUILayout.ObjectField(g, typeof(GameObject), true);
if (GUILayout.Button("Clone"))
{
clone = Instantiate<GameObject>(g);
EditorApplication.update += EngageRenameMode;
renameTime = EditorApplication.timeSinceStartup + 0.4d;
EditorApplication.ExecuteMenuItem("Window/General/Hierarchy");
Selection.activeGameObject = clone;
}
}
private void EngageRenameMode()
{
if (EditorApplication.timeSinceStartup >= renameTime)
{
EditorApplication.update -= EngageRenameMode;
var e = new Event { keyCode = KeyCode.F2, type = EventType.KeyDown }; // or Event.KeyboardEvent("f2");
EditorWindow.focusedWindow.SendEvent(e);
}
}
}
OBSOLETE:
Ok. Took me some time, but here you go:
using UnityEngine;
using UnityEditor;
using System.Reflection;
public class ObjClone : EditorWindow
{
// Add menu named "My Window" to the Window menu
[MenuItem("Window/ObjClone")]
static void Init()
{
// Get existing open window or if none, make a new one:
ObjClone window = (ObjClone)EditorWindow.GetWindow(typeof(ObjClone));
window.Show();
}
GameObject g;
GameObject clone;
volatile bool triggerRename;
private static double renameTime;
void OnGUI()
{
g = (GameObject)EditorGUILayout.ObjectField(g, typeof(GameObject), true);
if (GUILayout.Button("Clone"))
{
clone = Instantiate<GameObject>(g);
EditorApplication.update += EngageRenameMode;
renameTime = EditorApplication.timeSinceStartup + 0.4d;
EditorApplication.ExecuteMenuItem("Window/Hierarchy");
Selection.activeGameObject = clone;
}
}
private void EngageRenameMode()
{
if (EditorApplication.timeSinceStartup >= renameTime)
{
EditorApplication.update -= EngageRenameMode;
var type = typeof(EditorWindow).Assembly.GetType("UnityEditor.SceneHierarchyWindow");
var hierarchyWindow = EditorWindow.GetWindow(type);
var rename = type.GetMethod("RenameGO", BindingFlags.Instance | BindingFlags.NonPublic);
rename.Invoke(hierarchyWindow, null);
}
}
}