Skip to content

Instantly share code, notes, and snippets.

@Cayahuanca
Created March 13, 2025 16:13
Show Gist options
  • Save Cayahuanca/5e4f9e648b8355d1ceaaf3d79103509a to your computer and use it in GitHub Desktop.
Save Cayahuanca/5e4f9e648b8355d1ceaaf3d79103509a to your computer and use it in GitHub Desktop.
Auto Rename GameObject Name to Text_XXXXX (XXXXX from TextMeshPro's text)
using UnityEngine;
using UnityEditor;
using TMPro;
namespace Praecipua.EE
{
[InitializeOnLoad]
public static class TMP_NameUpdater
{
private static GameObject lastSelectedObject = null;
private static bool tmpUpdaterEnabled = true;
static TMP_NameUpdater()
{
Selection.selectionChanged += OnSelectionChanged;
}
[MenuItem("Window/Praecipua/TMP Auto Rename")]
private static void EnableTMPNameUpdater()
{
bool isChecked = Menu.GetChecked("Window/Praecipua/TMP Auto Rename");
Menu.SetChecked("Window/Praecipua/TMP Auto Rename", !isChecked);
tmpUpdaterEnabled = !isChecked;
lastSelectedObject = null;
}
private static void OnSelectionChanged()
{
if (!tmpUpdaterEnabled) return;
if (Selection.activeGameObject == lastSelectedObject) return;
if (lastSelectedObject != null)
{
if (lastSelectedObject.GetComponent<TextMeshPro>() != null)
{
UpdateTMPName(lastSelectedObject.GetComponent<TextMeshPro>());
}
else if (lastSelectedObject.GetComponent<TextMeshProUGUI>() != null)
{
UpdateTMPUName(lastSelectedObject.GetComponent<TextMeshProUGUI>());
}
}
lastSelectedObject = Selection.activeGameObject;
}
private static void UpdateTMPName(TextMeshPro tmp)
{
if (tmp == null || tmp.gameObject == null) return;
string text = tmp.text;
if (!string.IsNullOrEmpty(text))
{
string newName = "Text_" + text.Substring(0, Mathf.Min(5, text.Length));
if (tmp.gameObject.name != newName)
{
Undo.RecordObject(tmp.gameObject, "Rename TMP Object");
tmp.gameObject.name = newName;
}
}
}
private static void UpdateTMPUName(TextMeshProUGUI tmp)
{
if (tmp == null || tmp.gameObject == null) return;
string text = tmp.text;
if (!string.IsNullOrEmpty(text))
{
string newName = "Text_" + text.Substring(0, Mathf.Min(5, text.Length));
if (tmp.gameObject.name != newName)
{
Undo.RecordObject(tmp.gameObject, "Rename TMP Object");
tmp.gameObject.name = newName;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment