Created
April 15, 2025 21:29
-
-
Save FUJI-bayashi/952d0a5b410b89d507a63f1441ea3f51 to your computer and use it in GitHub Desktop.
Renames selected GameObjects in the Hierarchy based on their attached Sprite names from Image or SpriteRenderer components.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
using UnityEditor; | |
public static class RenameByAttachedImage | |
{ | |
/// <summary> | |
/// Called from the right-click context menu in the Hierarchy when objects are selected | |
/// </summary> | |
[MenuItem("GameObject/Rename By Attached Image", false, 0)] | |
private static void Rename() | |
{ | |
// Process all selected objects | |
foreach (GameObject go in Selection.gameObjects) | |
{ | |
// Get Image or SpriteRenderer component | |
Image imageComp = go.GetComponent<Image>(); | |
SpriteRenderer spriteRenderer = go.GetComponent<SpriteRenderer>(); | |
// If neither component is found, log a warning and skip | |
if (imageComp == null && spriteRenderer == null) | |
{ | |
Debug.LogWarning($"{go.name} does not have an Image or SpriteRenderer component"); | |
continue; | |
} | |
// If Image component exists | |
if (imageComp != null) | |
{ | |
if (imageComp.sprite == null) | |
{ | |
Debug.LogWarning($"No Sprite is attached to the Image on {go.name}"); | |
} | |
else | |
{ | |
string newName = imageComp.sprite.name; | |
go.name = newName; | |
Debug.Log($"Renamed to {go.name}"); | |
} | |
} | |
// If SpriteRenderer component exists | |
if (spriteRenderer != null) | |
{ | |
if (spriteRenderer.sprite == null) | |
{ | |
Debug.LogWarning($"No Sprite is attached to the SpriteRenderer on {go.name}"); | |
} | |
else | |
{ | |
string newName = spriteRenderer.sprite.name; | |
go.name = newName; | |
Debug.Log($"Renamed to {go.name}"); | |
} | |
} | |
} | |
} | |
/// <summary> | |
/// Enable the menu only when at least one object is selected | |
/// </summary> | |
[MenuItem("GameObject/Rename By Attached Image", true)] | |
private static bool ValidateRename() | |
{ | |
return Selection.activeGameObject != null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment