300x250
0. 개요
이전 글에서 분량 문제로 추가하지 못한 Insert, Delete, Update 기능을 추가하겠습니다.
1. 사전 작업
[Unity] RestApi 서버 이용하여 유저정보 관리 #1 (MySQL) :: 별빛상자 (tistory.com)
여기까지 되었다면 UI를 수정해주겠습니다.
1_1 UserCellView 수정
유저 데이터에 내용을 변경하면 좌상단에 체크 오브젝트를 표시해서 누를 경우 업데이트 내용이 서버에 반영되게 구현을 해볼 예정입니다.
우상단에 X 표시를 누를 경우엔 서버에 유저에 데이터 삭제 요청을 보낼 예정입니다.
1_2 신규유저 추가 버튼
우상단에 + 버튼을 추가하여 신규 유저를 추가할 수 있는 버튼을 만들었습니다. 해당버튼을 누르게 되면 신규유저 추가 화면이 나올 예정입니다.
2. UI 기능 작업
Packets.cs
using System.Collections.Generic;
public class Packets
{
public class user
{
public string user_id;
public string user_password;
public string user_name;
}
public class req_get_users
{
}
public class res_get_users
{
public int status_code;
public List<user> users;
}
public class req_insert_user
{
public string user_id;
public string user_password;
public string user_name;
}
public class res_insert_user
{
public int status_code;
}
public class req_delete_user
{
public string user_id;
}
public class res_delete_user
{
public int status_code;
}
public class req_update_user
{
public string user_id;
public string user_password;
public string user_name;
}
public class res_update_user
{
public int status_code;
}
}
HTTPManager에 서버의 정의해둔 Api를 호출하는 부분을 추가하겠습니다.
HTTPManager.cs
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
public class HTTPManager : MonoBehaviour
{
public static HTTPManager instance;
public UnityAction<List<Packets.user>> onGetUsers;
public void RequestUsers()
{
StartCoroutine(RequestUsersImpl());
}
public void RequestInsertUser(Packets.req_insert_user packet)
{
StartCoroutine(RequestInsertUserImpl(packet));
}
public void RequestDeleteUser(Packets.req_delete_user packet)
{
StartCoroutine(RequestDeleteUserImpl(packet));
}
public void RequestUpdateUser(Packets.req_update_user packet)
{
StartCoroutine(RequestUpdateUserImpl(packet));
}
private string _host = "http://localhost";
private int _port = 3000;
private void Awake()
{
instance = this;
}
private IEnumerator RequestInsertUserImpl(Packets.req_insert_user packet)
{
var url = string.Format("{0}:{1}{2}", _host, _port, "/users/insertUser");
Debug.Log(url);
var www = new UnityWebRequest(url, "POST");
// 객체를 => 문자열 직렬화
var json = JsonConvert.SerializeObject(packet);
// 문자열 => byte 배열로 직렬화
var rawdata = Encoding.UTF8.GetBytes(json);
www.uploadHandler = new UploadHandlerRaw(rawdata); // 요청
www.downloadHandler = new DownloadHandlerBuffer(); // 응답
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if(www.result == UnityWebRequest.Result.Success)
{
Debug.LogFormat("---->{0}", www.downloadHandler.text);
var res_signup = JsonConvert.DeserializeObject<Packets.res_insert_user>(www.downloadHandler.text); //역직렬화
Debug.LogFormat("status : {0}", res_signup.status_code);
}
else
{
Debug.LogFormat("에러");
}
}
private IEnumerator RequestDeleteUserImpl(Packets.req_delete_user packet)
{
var url = string.Format("{0}:{1}{2}", _host, _port, "/users/deleteUser");
Debug.Log(url);
var www = new UnityWebRequest(url, "POST");
// 객체를 => 문자열 직렬화
var json = JsonConvert.SerializeObject(packet);
// 문자열 => byte 배열로 직렬화
var rawdata = Encoding.UTF8.GetBytes(json);
www.uploadHandler = new UploadHandlerRaw(rawdata); // 요청
www.downloadHandler = new DownloadHandlerBuffer(); // 응답
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if(www.result == UnityWebRequest.Result.Success)
{
Debug.LogFormat("---->{0}", www.downloadHandler.text);
var res_signup = JsonConvert.DeserializeObject<Packets.res_insert_user>(www.downloadHandler.text); //역직렬화
Debug.LogFormat("status : {0}", res_signup.status_code);
}
else
{
Debug.LogFormat("에러");
}
}
private IEnumerator RequestUpdateUserImpl(Packets.req_update_user packet)
{
var url = string.Format("{0}:{1}{2}", _host, _port, "/users/updateUser");
Debug.Log(url);
var www = new UnityWebRequest(url, "POST");
// 객체를 => 문자열 직렬화
var json = JsonConvert.SerializeObject(packet);
// 문자열 => byte 배열로 직렬화
var rawdata = Encoding.UTF8.GetBytes(json);
www.uploadHandler = new UploadHandlerRaw(rawdata); // 요청
www.downloadHandler = new DownloadHandlerBuffer(); // 응답
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if(www.result == UnityWebRequest.Result.Success)
{
Debug.LogFormat("---->{0}", www.downloadHandler.text);
var res_signup = JsonConvert.DeserializeObject<Packets.res_insert_user>(www.downloadHandler.text); //역직렬화
Debug.LogFormat("status : {0}", res_signup.status_code);
}
else
{
Debug.LogFormat("에러");
}
}
private IEnumerator RequestUsersImpl()
{
var url = string.Format("{0}:{1}{2}", _host, _port, "/users/getUsers");
Debug.Log(url);
var www = new UnityWebRequest(url, "GET");
www.downloadHandler = new DownloadHandlerBuffer(); //응답
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.Success)
{
var res_get_users = JsonConvert.DeserializeObject<Packets.res_get_users>(www.downloadHandler.text);
if (res_get_users.status_code == 200)
{
onGetUsers(res_get_users.users);
}
}
else
{
Debug.Log("에러");
}
}
}
각각 Insert, Delete, Update에 대한 호출 부분을 추가하였습니다.
UserCellView.cs
using UnityEngine;
using UnityEngine.UI;
public class UserCellView : MonoBehaviour
{
public Text textUserId;
public InputField inputFieldPassword;
public InputField inputFieldUserName;
public GameObject submitBtnGo;
public void Init(Packets.user user)
{
_userId = user.user_id;
_password = user.user_password;
_userName = user.user_name;
textUserId.text = _userId;
inputFieldPassword.text = _password;
inputFieldUserName.text = _userName;
submitBtnGo.SetActive(false);
}
public void CheckUpdateInfo()
{
if (_isUpdate)
return;
// 유저 데이터를 변경한 경우
if (inputFieldPassword.text != _password || inputFieldUserName.text != _userName)
{
_isUpdate = true;
submitBtnGo.SetActive(true);
}
}
public void OnClickUpdate()
{
if (inputFieldPassword.text == "")
return;
if (inputFieldUserName.text == "")
return;
Packets.req_update_user packet = new Packets.req_update_user
{
user_id = _userId,
user_password = inputFieldPassword.text,
user_name = inputFieldUserName.text
};
HTTPManager.instance.RequestUpdateUser(packet);
TestMain.instance.Refresh();
}
public void OnClickDelete()
{
Packets.req_delete_user packet = new Packets.req_delete_user
{
user_id = _userId
};
HTTPManager.instance.RequestDeleteUser(packet);
TestMain.instance.Refresh();
}
private string _userId;
private string _password;
private string _userName;
private bool _isUpdate;
}
TestMain.cs
using UnityEngine;
using UnityEngine.UI;
public class TestMain : MonoBehaviour
{
public static TestMain instance;
public GameObject userCellviewPrefab;
public GameObject insertUserGo;
public RectTransform content;
public InputField inputFieldUserId;
public InputField inputFieldPassword;
public InputField inputFieldUserName;
public void OnClickShowInsertUser()
{
inputFieldUserId.text = "";
inputFieldPassword.text = "";
inputFieldUserName.text = "";
insertUserGo.SetActive(true);
}
public void OnClickHideInsertUser()
{
insertUserGo.SetActive(false);
}
public void OnClickInsertUser()
{
if (inputFieldUserId.text == "")
return;
if (inputFieldPassword.text == "")
return;
if (inputFieldUserName.text == "")
return;
Packets.req_insert_user packet = new Packets.req_insert_user
{
user_id = inputFieldUserId.text,
user_password = inputFieldPassword.text,
user_name = inputFieldUserName.text
};
HTTPManager.instance.RequestInsertUser(packet);
Refresh();
OnClickHideInsertUser();
}
public void Refresh()
{
foreach (Transform child in content)
{
Destroy(child.gameObject) ;
}
HTTPManager.instance.RequestUsers();
}
private void Start()
{
HTTPManager.instance.onGetUsers = (users) =>
{
foreach (var user in users)
{
var go = Instantiate<GameObject>(userCellviewPrefab, content);
var cellview = go.GetComponent<UserCellView>();
cellview.Init(user);
}
};
HTTPManager.instance.RequestUsers();
}
private void Awake()
{
instance = this;
}
}
3. 완성
감사합니다.
300x250
'[개인공부] > Unity' 카테고리의 다른 글
[Unity] Built In Standard Shader => URP Shader 변경 (0) | 2024.06.09 |
---|---|
[Unity Error - 해결] 빌드 에러 Android SDK is missing required plaform API (0) | 2024.04.03 |
[Unity] Rest Api 서버 이용하여 유저정보 관리 #1 (MySQL) (2) | 2023.11.30 |
[Unity Error] unity is running as administrator (0) | 2023.09.03 |
[Unity] Content Size Fitter 버그 증상 임시 (0) | 2023.08.24 |