Skip to content

Instantly share code, notes, and snippets.

@seiroise
Last active August 15, 2018 06:12
Show Gist options
  • Select an option

  • Save seiroise/ebb9f073cc7994da398758eb49b3c8cb to your computer and use it in GitHub Desktop.

Select an option

Save seiroise/ebb9f073cc7994da398758eb49b3c8cb to your computer and use it in GitHub Desktop.
Hierarchy上の選択したGameObjectの名前を一括で変更する
#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Text.RegularExpressions;
namespace Seiro.Utils
{
public class RegexWindow : EditorWindow
{
[SerializeField]
string _pattern = "";
[SerializeField]
string _replacement = "";
[SerializeField]
bool _serialNumber = false;
void DoRename()
{
// 選択している中からGameObjectでMainなもの(PrefabのRootなど)だけとりだし
var targets = Selection.gameObjects.Where(t => !AssetDatabase.IsMainAsset(t)).ToArray();
Undo.RecordObjects(targets, "Regex Rename");
// 連番を振る場合、SelectionがHierarchy上の見かけの順番と異なる場合があるので、ソートした方がよい。
if (_serialNumber)
{
SortWithSibling(targets);
}
for (int i = 0, n = targets.Length; i < n; ++i)
{
var t = targets[i];
var rep = "";
if (_serialNumber)
{
rep = string.Format(_replacement, i);
}
else
{
rep = _replacement;
}
t.name = Regex.Replace(t.name, _pattern, rep);
}
}
void SortWithSibling(GameObject[] src)
{
System.Array.Sort(src, (a, b) => a.transform.GetSiblingIndex() - b.transform.GetSiblingIndex());
}
void OnGUI()
{
_pattern = EditorGUILayout.TextField("Pattern", _pattern);
_replacement = EditorGUILayout.TextField("Replacement", _replacement);
_serialNumber = EditorGUILayout.Toggle("Serial Number", _serialNumber);
EditorGUI.BeginDisabledGroup(Selection.gameObjects.Length == 0);
if (GUILayout.Button("Do Rename"))
{
DoRename();
}
EditorGUI.EndDisabledGroup();
}
[MenuItem("Window/Seiro/Regex")]
public static void Open()
{
GetWindow<RegexWindow>();
}
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment