반응형
문제점
Resources 폴더안에 Json을 생성해놓고 불러와서 읽고 쓰게 하고싶었는데 이미 빌드중인 상태일때는 파일을 동적으로 수정하거나 할때는 사용하지않는다고 해서 고민을 했다.
아직 본격적인 프로젝트가 아닌데 서버를 만들어서 하기에는 좀 헤비하다고 생각했고 간단하게 로그인 시스템을 구현할 수 있을 것 같다고 생각해서 열심히 찾아봤다.
해결 방법
[Unity] 유니티 저장 경로(dataPath, streamingAssetsPath, persistentDataPath 경로와 차이점)
[서문] 게임을 만드는 도중, 세이브/로드가 잘 안 먹히는 현상때문에 골머리를 앓았는데요, 실시간으로 인게임에서 데이터를 불러오고 저장하는게 잘 안 되는 현상이었습니다. (에디터 밖으로
geukggom.tistory.com
이분의 블로그를 보면 나랑 똑같은 고민을 하신 흔적이 보인다.
회원가입시 아이디와 비밀번호를 Json파일에 저장해야하기 때문에
Application.persistentDataPath를 사용했다.
그렇게 코드를 수정하고 저장경로에서 확인을 해보면 성공적으로 원하는 모습이 저장되어있다.
코드
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using System.IO;
using UnityEngine.SceneManagement;
using System;
[System.Serializable]
public class User
{
public string id;
public string password;
}
[System.Serializable]
public class UserList
{
public List<User> users;
}
public class PlayerJoinManager : MonoBehaviour
{
public TMP_InputField idField;
public TMP_InputField passWordField;
public Text idWarningTxt;
public Text passWordWarningTxt;
public Button joinCheckBtn;
private string userInfoFilePath;
public event Action UserAddedSuccessfully;
void Start()
{
userInfoFilePath = Path.Combine(Application.persistentDataPath, "PlayerInfo.json");
if (!File.Exists(userInfoFilePath))
{
UserList emptyUserList = new UserList { users = new List<User>() };
string emptyJson = JsonUtility.ToJson(emptyUserList, true);
File.WriteAllText(userInfoFilePath, emptyJson);
}
idWarningTxt.gameObject.SetActive(false);
passWordWarningTxt.gameObject.SetActive(false);
joinCheckBtn.onClick.AddListener(OnJoinCheckBtnClick);
}
void OnJoinCheckBtnClick()
{
string id = idField.text;
string password = passWordField.text;
if (IdCheck(id))
{
idWarningTxt.gameObject.SetActive(true);
}
else
{
idWarningTxt.gameObject.SetActive(false);
}
if (!PasswordCheck(password))
{
passWordWarningTxt.gameObject.SetActive(true);
}
else
{
passWordWarningTxt.gameObject.SetActive(false);
}
if (!IdCheck(id) && PasswordCheck(password))
{
SaveUser(id, password);
UserAddedSuccessfully?.Invoke();
}
}
bool IdCheck(string id)
{
if (File.Exists(userInfoFilePath))
{
string json = File.ReadAllText(userInfoFilePath);
UserList userList = JsonUtility.FromJson<UserList>(json);
if (userList != null && userList.users != null)
{
foreach (var user in userList.users)
{
if (user.id == id)
{
return true;
}
}
}
}
return false;
}
bool PasswordCheck(string password)
{
return password.Length >= 4 && password.Length <= 12;
}
void SaveUser(string id, string password)
{
if (string.IsNullOrEmpty(userInfoFilePath))
{
Debug.LogError("userInfoFilePath is null or empty!");
return;
}
User newUser = new User { id = id, password = password };
UserList userList;
if (File.Exists(userInfoFilePath))
{
string json = File.ReadAllText(userInfoFilePath);
if (string.IsNullOrEmpty(json))
{
userList = new UserList { users = new List<User>() };
}
else
{
userList = JsonUtility.FromJson<UserList>(json);
}
}
else
{
userList = new UserList { users = new List<User>() };
}
if (userList.users == null)
{
userList.users = new List<User>();
}
userList.users.Add(newUser);
string newJson = JsonUtility.ToJson(userList, true);
File.WriteAllText(userInfoFilePath, newJson);
}
}
오늘의 회고
리소스 폴더는 쓰기가 안된다는걸 이번에 처음알았는데 서버를 쓰지도않고 유니티에서도 쉽게 저장할 수 있는 방법을 알게되어 뿌듯하고,
오늘은 팀원들이랑 기능을 모두 병합하는데 충돌도 안나고 꽤 재미있었던 하루였다.
근데 오늘 진짜 하루종일 졸려서 계속 졸았다........... 정신차리자!!
반응형
'Record > TIL' 카테고리의 다른 글
[Unity] Dictionary TryGetValue 메서드 활용하기 (ContainsKey와 차이점) (0) | 2024.05.21 |
---|---|
[Unity] Unity Toggle 사용하기 (0) | 2024.05.20 |
[Unity] 결합도와 응집도 (4) | 2024.05.16 |
[Unity] 탑다운뷰 게임 개인프로젝트 마무리 (2) | 2024.05.14 |
[Unity] 스크롤뷰 사용해서 참석인원 불러오기 (1) | 2024.05.13 |