씬 전환 기능 및 씬이 변경되어도 플레이어 정보를 유지하도록 게임 매니저 구현

This commit is contained in:
김민구
2026-07-08 04:24:12 +09:00
parent 8f742e50d9
commit 6939015d9e
8 changed files with 456 additions and 25 deletions
@@ -0,0 +1,42 @@
using UnityEngine;
public class GameManager : MonoBehaviour
{
// 외부에서 쉽게 접근할 수 있는 싱글톤 인스턴스
public static GameManager Instance { get; private set; }
[Header("보존할 플레이어 스탯 데이터")]
public string playerName = "";
public int playerGeneration = 1;
public int playerHp = 5;
public int playerMaxHp = 5;
private void Awake()
{
// 중복 생성 방지 및 싱글톤 유지
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
// 씬이 전환되어도 이 오브젝트가 파괴되지 않고 유지되도록 설정합니다.
DontDestroyOnLoad(gameObject);
}
// 플레이어 스탯을 동기적으로 복사하여 세이브하는 메서드
public void SavePlayerData(Player player)
{
if (player != null)
{
playerName = player.CharacterName;
playerGeneration = player.Generation;
playerHp = player.hp;
playerMaxHp = player.maxHp;
Debug.Log($"[GameManager] 캐릭터 정보 보존 세이브 완료: {playerName} ({playerGeneration}대) | HP: {playerHp}/{playerMaxHp}");
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d42f0450bff4242dca327151c2892fb6
+31 -5
View File
@@ -33,7 +33,7 @@ public class Player : MonoBehaviour
[SerializeField] public int hp = 5;
[SerializeField] public int maxHp = 5;
private bool isFacingRight = false;
private bool isFacingRight = true;
private int currentAnimationState = -1;
private Animator animator;
@@ -69,9 +69,9 @@ public class Player : MonoBehaviour
Debug.LogError($"{gameObject.name} 오브젝트에 SPUM_Prefabs 컴포넌트가 없습니다! 인스펙터를 확인하세요.");
}
// 캐릭터 방향 기본 오른쪽 설정
// 오리지널 리소스가 원래 왼쪽을 보고 있으므로, 시작 시 X 스케일을 반전시켜 즉시 오른쪽을 바라보도록 초기화합니다.
Vector3 initialScale = transform.localScale;
initialScale.x = Mathf.Abs(initialScale.x);
initialScale.x = -Mathf.Abs(initialScale.x);
transform.localScale = initialScale;
animator = GetComponentInChildren<Animator>();
@@ -80,8 +80,34 @@ public class Player : MonoBehaviour
void Start()
{
// 시작 시 백엔드로부터 다음 세대 정보 조회
StartCoroutine(GetNextGenerationFromServer());
// 씬 로딩 후 GameManager에 이미 보존되어 넘어온 캐릭터 정보가 존재한다면 복구합니다.
if (GameManager.Instance != null && !string.IsNullOrEmpty(GameManager.Instance.playerName))
{
characterName = GameManager.Instance.playerName;
generation = GameManager.Instance.playerGeneration;
hp = GameManager.Instance.playerHp;
maxHp = GameManager.Instance.playerMaxHp;
// UI 텍스트 및 이미지 게이지 동기화
if (nameText != null)
{
nameText.text = characterName;
}
if (hpImage != null && maxHp > 0)
{
float fillRatio = Mathf.Clamp01((float)hp / maxHp);
hpImage.fillAmount = fillRatio;
hpImage.rectTransform.localScale = new Vector3(fillRatio, 1f, 1f);
}
Debug.Log($"[Player] GameManager로부터 이전 캐릭터 정보를 무사히 인계받았습니다: {characterName} | HP: {hp}/{maxHp}");
}
else
{
// 데이터가 보존되지 않은 최초 기동 상태인 경우에만 백엔드 서버에서 신규 세대 번호를 조회하여 할당합니다.
StartCoroutine(GetNextGenerationFromServer());
}
}
private void Update()
@@ -0,0 +1,44 @@
using UnityEngine;
using UnityEngine.SceneManagement;
[RequireComponent(typeof(Collider2D))] // 트리거 판정을 위해 Collider2D가 부착되어 있어야 합니다.
public class WallTransition : MonoBehaviour
{
[Header("전환될 목표 씬 이름")]
[SerializeField] private string targetSceneName = "battleStage";
private void Start()
{
// 물리적인 밀어냄 현상을 방지하고 통과 감지만 할 수 있도록 트리거(Trigger)로 지정합니다.
Collider2D col = GetComponent<Collider2D>();
if (col != null && !col.isTrigger)
{
col.isTrigger = true;
Debug.LogWarning($"[Transition] {gameObject.name}에 부착된 Collider2D를 트리거(Is Trigger = true)로 자동 갱신했습니다.");
}
}
private void OnTriggerEnter2D(Collider2D other)
{
// 닿은 물체가 플레이어 캐릭터인지 확인합니다.
Player player = other.GetComponent<Player>();
if (player != null)
{
Debug.Log($"[Transition] 플레이어 '{player.CharacterName}'가 우측 경계 성벽에 접촉했습니다.");
// 1. 싱글톤 GameManager 인스턴스가 존재할 경우 현재 플레이어의 정보(이름, 세대, HP)를 세이브합니다.
if (GameManager.Instance != null)
{
GameManager.Instance.SavePlayerData(player);
}
else
{
Debug.LogWarning("[Transition] 씬에 GameManager 싱글톤 오브젝트가 존재하지 않아 플레이어 정보 임시 세이브를 스킵합니다.");
}
// 2. 유니티 씬 매니저를 통해 목표 씬(battleStage)을 즉시 로드합니다.
Debug.Log($"[Transition] {targetSceneName} 씬으로 화면을 전환합니다.");
SceneManager.LoadScene(targetSceneName);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0e728dcba3a32418da46f86eb0b8a001