KDT Unity 5주차 팀 프로젝트
2024-02-01 TIL
플레이어의 저장된 정보를 불러오는 것은 되지만 저장이 안되는 문제
해결 방안 1 json파일을 어드레서블로 가져와 불러오기를 사용 하지만 어드레서블 파일은 읽기 전용으로 가져와져 저장이 사용 불가
해결 방안 2 리소스 파일에서 가져와 사용 해당 방법도 읽기 전용으로 불러와져 사용 불가
해결 방안 3 초기 데이터 파일을 리소스 파일에 저장후 해당 파일이 데이터 파일에 없으면 복사후 사용하는 방법을 채택
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public void CheckFile(string fileName)
{
string persistentPath = Path.Combine(Application.persistentDataPath, fileName); // 데이터 폴더의 파일 경로
// 데이터 폴더에 파일이 없으면 "Resources" 폴더에서 복사
if (!File.Exists(persistentPath))
{
TextAsset textAsset = Resources.Load<TextAsset>(fileName); // "Resources" 폴더에서 파일 읽기
File.WriteAllText(persistentPath, textAsset.text); // 데이터 폴더에 파일 쓰기
}
}
/// <summary>
/// json파일을 읽어오는 메서드
/// </summary>
/// <returns></returns>
public StageClear Lord()
{
string fileName = "PlayerDate";
CheckFile(fileName);
string persistentPath = Path.Combine(Application.persistentDataPath, fileName); // 데이터 폴더의 파일 경로
// 데이터 폴더의 파일에서 JSON 문자열 읽기
string json = File.ReadAllText(persistentPath);
// JSON 문자열을 객체로 변환
StageClear stageClear = JsonConvert.DeserializeObject<StageClear>(json);
return stageClear;
}
/// <summary>
/// 한번에 모든 데이터를 바꾸는 메서드
/// </summary>
/// <param name="stageDate"></param>
public void ModifyWrite(StageClear stageDate)
{
string fileName = "PlayerDate";
CheckFile(fileName);
string persistentPath = Path.Combine(Application.persistentDataPath, fileName); // 데이터 폴더의 파일 경로
// 객체를 다시 JSON 문자열로 변환
string newJson = JsonConvert.SerializeObject(stageDate);
// JSON 문자열을 데이터 폴더의 파일에 저장
File.WriteAllText(persistentPath, newJson);
}
This post is licensed under CC BY 4.0 by the author.