우당탕탕 개발일지

[커스텀 에디터] 파일 이름에서 ID추출 & 자동 ID부여하기 본문

Unity

[커스텀 에디터] 파일 이름에서 ID추출 & 자동 ID부여하기

devchop 2025. 4. 8. 22:16

 

목표

  • 파일이름을 1_이름  포맷으로 저장하면, ID = 1로 자동으로 설정한다. 파일 이름을 수정할 경우 ID도 그에 맞게 변경된다.
  • 새로운 ScriptableObject를 생성할 때, 현재 정의되어있는ID들중 가장 큰 id + 1로 id를 새로 설정한다.

 

GoldStatData에 적용을 해볼것이다.  원래 ScripatbleObject에 CreateAssetMenu라는 키워드를 붙여서 새로운 오브젝트를 생성할 수 있게 했었는데, 이부분을 제거해야한다. CustoemEditor 부분에서 구현해줄 예정이다.

public class GoldStatData : ScriptableObject{
	public int id;
}

 

 

GoldStatDataEditor 주요 코드

using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(GoldStatData))]
[CanEditMultipleObjects]
public class GoldStatDataEditor : Editor
{
    protected SerializedProperty id;
    //...
   
    public void OnEnable()
    {
        var parsedId = EditorUtils.ParseIDFromFileName(target);
        var statData = (GoldStatData)target;
        if (statData.id != parsedId)
        {
            statData.id = parsedId;
            EditorUtility.SetDirty(target); // 변경 사항 저장
        }
    }

    public override void OnInspectorGUI()
    {
        serializedObject.Update();
        //...
		DrawInfo();

        serializedObject.ApplyModifiedProperties();
    }

    void DrawInfo()
    {
        //...
        //ID를 직접 수정하지 못하도록 disable처리

        EditorGUI.BeginDisabledGroup(true);
        EditorGUILayout.IntField("ID", id.intValue);
        EditorGUI.EndDisabledGroup();

    }
    
    
    //Create > New Gold Stat을 눌러 새로운 ScriptableObject를 생성할 때 ID를 설정한다.
    [MenuItem("Assets/Create/Stats/New Gold Stat")]
    public static void CreateMyData()
    {
        string folderPath = EditorUtils.GetSelectedPathOrFallback();
        string[] guids = AssetDatabase.FindAssets("t:GoldStatData");
        int maxId = 0;

        foreach (string guid in guids)
        {
            string path = AssetDatabase.GUIDToAssetPath(guid);
            GoldStatData existingData = AssetDatabase.LoadAssetAtPath<GoldStatData>(path);

            if (existingData != null)
            {
                maxId = Mathf.Max(maxId, existingData.id);
            }
        }

        // 3. 새로운 데이터 생성
        int newId = maxId + 1;
        GoldStatData newData = ScriptableObject.CreateInstance<GoldStatData>();
        newData.id = newId;
        newData.title = "New Gold Stat"; // 기본 제목 설정 (원하면 다이얼로그나 입력도 가능)

        // 4. 파일 이름 구성: 예) "4_새로운스탯.asset"
        string safeTitle = newData.title.Replace(" ", "").Replace("/", ""); // 파일 이름 안전하게
        string fileName = $"{newId}_{safeTitle}.asset";
        string assetPath = AssetDatabase.GenerateUniqueAssetPath(System.IO.Path.Combine(folderPath, fileName));

        // 5. 에셋 저장
        AssetDatabase.CreateAsset(newData, assetPath);
        AssetDatabase.SaveAssets();

        EditorUtility.FocusProjectWindow();
        Selection.activeObject = newData;
    }
}

 

 

OnEnable 시에 ID를 알맞게 설정하기

  1. 현재 파일 이름에서, 맨 앞부분 숫자 부분만 추출한다.
  2. 현재ID와 추출된 ID가 다를 경우 변경하고 저장해준다
public static int ParseIDFromFileName(Object data)
    {
        // 에디터에서 열릴 때 파일 이름으로부터 ID 자동 설정
        string assetPath = AssetDatabase.GetAssetPath(data);
        string fileName = System.IO.Path.GetFileNameWithoutExtension(assetPath);

        if (int.TryParse(fileName.Split('_')[0], out int parsedId))
        {
            return parsedId;
        }
        return 0;

    }

 

새로운 오브젝트 생성 시 새로운 ID를 부여하기

  1. 동일한 타입 (GoldStatData) 의 데이터를 모두 가져와서, ID중 가장 큰 값 maxID를 찾는다.
  2. 현재 선택된 path를 가져와, 새로운 이름을 붙인 경로를 생성 및 저장한다.

 

// 현재 선택된 폴더 또는 기본 폴더(Assets/) 반환
    public static string GetSelectedPathOrFallback()
    {
        string path = "Assets";

        foreach (Object obj in Selection.GetFiltered(typeof(Object), SelectionMode.Assets))
        {
            string assetPath = AssetDatabase.GetAssetPath(obj);
            if (Directory.Exists(assetPath))
            {
                path = assetPath;
                break;
            }
            else if (!string.IsNullOrEmpty(assetPath))
            {
                path = Path.GetDirectoryName(assetPath);
                break;
            }
        }

        return path.Replace("\\", "/");
    }

 

이제 파일을 생성하면, 다음과 같이 1_Power 처럼 맨앞에 ID가 설정된 것을 볼 수 있다. 파일이름을 수정할 경우 , ID도 같이 변경된다.

ID는 직접 수정할 수 없고, 확인만 가능하다. 만약 ID를 변경하고싶다면 파일 이름에서 변경하면된다.

 

scriptable object의 네이밍 샘플
ID부분은 확인가능하지만 회색으로, 수정이 불가능하다.

 

 

 

조금더 개선하고싶은 부분은, ID가 동일한 파일이 있을 경우 수정이 불가능하게 막는건데.. 이건 다음에 개선하고 포스팅 하도록 하겠다!