unity項(xiàng)目中,需要保存,加載大量的數(shù)據(jù)信息,對(duì)于unity直接編寫訪問數(shù)據(jù)庫的代碼畢竟麻煩。而java中的ruoyi框架可以直接根據(jù)數(shù)據(jù)庫表生成對(duì)應(yīng)的java后臺(tái),unity調(diào)用java后臺(tái)的接口即可完成數(shù)據(jù)保存和加載。代碼如下:文章來源:http://www.zghlxwxcb.cn/news/detail-662997.html
using UnityEngine.Networking;
using Newtonsoft.Json;
public class LoginBody
{
public string username;
public string password;
public LoginBody(string username, string password)
{
this.username = username;
this.password = password;
}
}
public class ResponseLogin
{
public string msg;//信息內(nèi)容
public int code;//內(nèi)容編號(hào)
public SysUser data;//用戶(結(jié)構(gòu)體,內(nèi)容就不展示了,看你的java后端傳回的參數(shù)是哪些)
public string token;//令牌
}
public class Login:MonoBehaviour
{
public static string URL = "http://localhost:8080";//后端網(wǎng)頁地址
public static string token;//賬號(hào)令牌
public IEnumerator LoginCoroutine()
{
LoginBody login = new LoginBody(username,password);
byte[] jsonArray = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(login));
UnityWebRequest loginRequest = new UnityWebRequest(URL+"/login","POST");
loginRequest.uploadHandler = new UploadHandlerRaw(jsonArray);
loginRequest.downloadHandler = new DownloadHandlerBuffer();
loginRequest.SetRequestHeader("Content-Type","application/json");
//loginRequest.SetRequestHeader("Authorization","Bearer" + token);//對(duì)于需要訪問權(quán)限的后臺(tái)需要傳遞登錄賬號(hào)的令牌才能訪問數(shù)據(jù)
yield return loginRequest.SendWebRequest();
ResponseLogin response = JsonUtility.FromJson<ResponseLogin>(loginRequest.downloadHandler.text);
if(response.code == 200)
UnityEngine.Debug.Log(“賬號(hào)密碼驗(yàn)證通過,成功獲取該賬號(hào)的登錄請(qǐng)求!”);
else
UnityEngine.Debug.Log("登錄失敗,錯(cuò)誤代碼:" + response.code + "信息:" + response.msg);
}
}
代碼很簡(jiǎn)單,但是其中涉及到的內(nèi)容需要和Java后臺(tái)開發(fā)人員溝通,查詢傳遞的內(nèi)容以及接收的數(shù)據(jù),都需要保證在結(jié)構(gòu)體中其變量名是一模一樣的,不然無法傳遞值。文章來源地址http://www.zghlxwxcb.cn/news/detail-662997.html
到了這里,關(guān)于Unity通過訪問java后臺(tái)獲取數(shù)據(jù)庫數(shù)據(jù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!