using System.Collections.Generic; using System.IO; using System.Linq; using Platformer.Gameplay; using Platformer.Mechanics; using UnityEditor; using UnityEditor.Animations; using UnityEngine; /// /// 리뉴얼 2026-11-10 (PD 지시) — 새 캐릭터(Hero2) 스프라이트 교체 + 근접 자동 공격 부착. /// 값 SOT = Assets/Character/Sprites/Hero2/hero2_import.json (finalize_frames.py 산출 · 캔버스·기준점·PPU·클립 구성). /// 발 위치 = Player 프리팹 콜라이더 바닥에서 계산(값 중복 없음). /// public static class Hero2RenewalSetup { const string Hero2Dir = "Assets/Character/Sprites/Hero2"; const string ClipDir = "Assets/Character/Animations/Hero2"; const string PlayerPrefab = "Assets/Prefabs/Player.prefab"; const string BaseController = "Assets/Character/Animations/Player.controller"; const string OverridePath = "Assets/Character/Animations/Hero2/Hero2.overrideController"; [System.Serializable] class ClipCfg { public string[] frames; public float fps; public bool loop; public float[] times; public float length; } [System.Serializable] class ClipSet { public ClipCfg run, attack, jump; } [System.Serializable] class ImportCfg { public int[] canvas; public float[] anchor_px_from_top_left; public float ppu; public ClipSet clips; } static ImportCfg LoadCfg() => JsonUtility.FromJson(File.ReadAllText(Path.Combine(Hero2Dir, "hero2_import.json"))); /// 프리팹 콜라이더 바닥(로컬 y, 스케일 적용 전). static float ColliderBottomLocal(GameObject root) { var box = root.GetComponent(); if (box != null) return box.offset.y - box.size.y * 0.5f - box.edgeRadius; var cap = root.GetComponent(); if (cap != null) return cap.offset.y - cap.size.y * 0.5f; var circle = root.GetComponent(); if (circle != null) return circle.offset.y - circle.radius; throw new System.Exception("Player 콜라이더를 찾지 못함"); } [MenuItem("Tools/Renewal/1. Hero2 Import Settings")] public static string ImportSprites() { var cfg = LoadCfg(); var prefab = AssetDatabase.LoadAssetAtPath(PlayerPrefab); float feetLocal = ColliderBottomLocal(prefab); float W = cfg.canvas[0], H = cfg.canvas[1]; float ax = cfg.anchor_px_from_top_left[0], ay = cfg.anchor_px_from_top_left[1]; // 발 픽셀 행(ay, 위에서) 이 콜라이더 바닥(feetLocal) 에 오도록 기준점 y 를 정한다. var pivot = new Vector2(ax / W, (H - ay - feetLocal * cfg.ppu) / H); int n = 0; foreach (var guid in AssetDatabase.FindAssets("t:Texture2D", new[] { Hero2Dir })) { var path = AssetDatabase.GUIDToAssetPath(guid); var ti = (TextureImporter)AssetImporter.GetAtPath(path); ti.textureType = TextureImporterType.Sprite; ti.spriteImportMode = SpriteImportMode.Single; var s = new TextureImporterSettings(); ti.ReadTextureSettings(s); s.spriteAlignment = (int)SpriteAlignment.Custom; s.spritePivot = pivot; s.spritePixelsPerUnit = cfg.ppu; s.spriteMeshType = SpriteMeshType.FullRect; s.alphaIsTransparency = true; s.mipmapEnabled = false; s.filterMode = FilterMode.Bilinear; s.wrapMode = TextureWrapMode.Clamp; ti.SetTextureSettings(s); ti.textureCompression = TextureImporterCompression.CompressedHQ; ti.SaveAndReimport(); n++; } return $"import {n} sprites · ppu {cfg.ppu} · pivot {pivot.x:F4},{pivot.y:F4} · feetLocal {feetLocal:F4}"; } static Sprite S(string name) => AssetDatabase.LoadAssetAtPath($"{Hero2Dir}/{name}.png"); static AnimationClip MakeClip(string clipName, string[] frames, float[] times, float length, bool loop) { Directory.CreateDirectory(ClipDir); string path = $"{ClipDir}/{clipName}.anim"; var clip = AssetDatabase.LoadAssetAtPath(path); if (clip == null) { clip = new AnimationClip { frameRate = 60 }; AssetDatabase.CreateAsset(clip, path); } clip.ClearCurves(); var binding = EditorCurveBinding.PPtrCurve("", typeof(SpriteRenderer), "m_Sprite"); var keys = new List(); for (int i = 0; i < frames.Length; i++) keys.Add(new ObjectReferenceKeyframe { time = times[i], value = S(frames[i]) }); // 마지막 프레임을 끝 시각까지 유지(클립 길이 = length) keys.Add(new ObjectReferenceKeyframe { time = length, value = S(frames[frames.Length - 1]) }); AnimationUtility.SetObjectReferenceCurve(clip, binding, keys.ToArray()); var st = AnimationUtility.GetAnimationClipSettings(clip); st.loopTime = loop; AnimationUtility.SetAnimationClipSettings(clip, st); EditorUtility.SetDirty(clip); return clip; } static AnimationClip MakeFpsClip(string clipName, ClipCfg c) { float dt = 1f / c.fps; var times = Enumerable.Range(0, c.frames.Length).Select(i => i * dt).ToArray(); // 반복 클립은 마지막 키를 한 칸 뒤(= 첫 프레임 직전)에 두어 모든 프레임이 같은 시간 보이게 한다. return MakeClip(clipName, c.frames, times, c.frames.Length * dt - (c.loop ? 0.0001f : 0f), c.loop); } [MenuItem("Tools/Renewal/2. Hero2 Clips + Override")] public static string BuildAnimation() { var cfg = LoadCfg(); var run = MakeFpsClip("Hero2_Run", cfg.clips.run); var attack = MakeClip("Hero2_Attack", cfg.clips.attack.frames, cfg.clips.attack.times, cfg.clips.attack.length, false); var jump = MakeFpsClip("Hero2_Jump", cfg.clips.jump); // 대기·피격·사망·부활 전용 그림은 아직 없다 → 달리기 첫 프레임 정지 그림으로 대신(보고에 명시). var still = MakeClip("Hero2_Still", new[] { cfg.clips.run.frames[0] }, new[] { 0f }, 0.1f, true); var hit = MakeClip("Hero2_Hit", new[] { cfg.clips.run.frames[1] }, new[] { 0f }, 0.2f, false); var baseCtrl = AssetDatabase.LoadAssetAtPath(BaseController); var ov = AssetDatabase.LoadAssetAtPath(OverridePath); if (ov == null) { ov = new AnimatorOverrideController(baseCtrl); AssetDatabase.CreateAsset(ov, OverridePath); } ov.runtimeAnimatorController = baseCtrl; var byState = new Dictionary { { "Player-Run", run }, { "Player-Attack", attack }, { "Player-Jump", jump }, { "Player-Idle", still }, { "Player-CombatIdle", still }, { "Player-Hit", hit }, { "Player-Death", still }, { "Player-Resurrection", still }, }; var pairs = new List>(); var log = new List(); foreach (var cs in baseCtrl.layers[0].stateMachine.states) { var orig = cs.state.motion as AnimationClip; if (orig == null) { log.Add($"{cs.state.name}: (클립 아님)"); continue; } if (byState.TryGetValue(cs.state.name, out var nc)) { pairs.Add(new KeyValuePair(orig, nc)); log.Add($"{cs.state.name}: {orig.name}->{nc.name}"); } else log.Add($"{cs.state.name}: {orig.name} (그대로)"); } ov.ApplyOverrides(pairs); EditorUtility.SetDirty(ov); AssetDatabase.SaveAssets(); return string.Join(" | ", log); } [MenuItem("Tools/Renewal/3. Apply Hero2 To Player Prefab")] public static string ApplyToPrefab() { var root = PrefabUtility.LoadPrefabContents(PlayerPrefab); try { var cfg = LoadCfg(); var sr = root.GetComponent(); sr.sprite = S(cfg.clips.run.frames[0]); var anim = root.GetComponent(); anim.runtimeAnimatorController = AssetDatabase.LoadAssetAtPath(OverridePath); var pc = root.GetComponent(); pc.autoRun = true; var ticker = root.GetComponent(); if (ticker == null) ticker = root.AddComponent(); ticker.onlyWhenEnemyNear = true; if (pc.attackHitbox == null) pc.attackHitbox = root.GetComponent(); PrefabUtility.SaveAsPrefabAsset(root, PlayerPrefab); } finally { PrefabUtility.UnloadPrefabContents(root); } // 기본 그림은 프리팹 편집 장면에서 저장되지 않는 경우가 있어(2026-11-10 실측) 에셋에 직접 한 번 더 넣는다. var asset = AssetDatabase.LoadAssetAtPath(PlayerPrefab); var assetSr = asset.GetComponent(); var first = S(LoadCfg().clips.run.frames[0]); if (assetSr.sprite != first) { assetSr.sprite = first; EditorUtility.SetDirty(asset); PrefabUtility.SavePrefabAsset(asset); } var a2 = asset.GetComponent(); return $"prefab ok · sprite {assetSr.sprite?.name} · ctrl {a2.runtimeAnimatorController?.name} · ticker {asset.GetComponent() != null}"; } }