iT邦幫忙

2024 iThome 鐵人賽

DAY 16
0

要如何串接任意的API格式到遊戲中?
包含OpenAI, Google, 其他HTTP API

1. 了解要串接的的API接收和回傳的Json格式

API接收的JSON格式:

{
    "id": 1
}

API回傳的JSON格式:

{
    "id": 1,
    "name": "John Doe",
    "email": "johndoe@example.com",
    "age": 30
}

2. 使用JsonToC#

https://ithelp.ithome.com.tw/upload/images/20240828/20119470MDnsod2a85.png

https://json2csharp.com/

上面的案例比較簡單
但如果遇到比較複雜的格式
我們可以直接使用現成的工具
把Json格式轉換成C#的Class

3. 使用Unity Web Request去呼叫和提取API

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using Newtonsoft.Json;

public class APIClient : MonoBehaviour
{
    private string apiUrl = "https://api.example.com/data";

    // Action for handling the processed data
    public System.Action<PlayerData> OnDataReceived;

    // POST request to send JSON data
    public IEnumerator PostRequest(int playerId)
    {
        PlayerRequestData requestData = new PlayerRequestData { Id = playerId };
        string json = JsonConvert.SerializeObject(requestData);

        UnityWebRequest request = new UnityWebRequest(apiUrl, "POST");
        byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
        request.uploadHandler = new UploadHandlerRaw(jsonToSend);
        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");

        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.Success)
        {
            string jsonResponse = request.downloadHandler.text;
            ProcessResponse(jsonResponse);
        }
        else
        {
            Debug.LogError("Error: " + request.error);
        }
    }

    private void ProcessResponse(string jsonResponse)
    {
        // Process and map the JSON response to the PlayerData class
        PlayerData playerData = JsonConvert.DeserializeObject<PlayerData>(jsonResponse);

        // Invoke the action if it's not null
        OnDataReceived?.Invoke(playerData);
    }
}

// Class to represent the request data
public class PlayerRequestData
{
    public int Id { get; set; }
}

// Class to represent the response data
public class PlayerData
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
}

  1. 使用Newtonsoft JsonConvert 換成Class

我們在這一步可以把回傳的json轉成可以使用的Class


private void ProcessResponse(string jsonResponse)
{
    // 將JSON響應轉換為PlayerData對象
    PlayerData player = JsonConvert.DeserializeObject<PlayerData>(jsonResponse);

    // 處理並使用轉換後的數據
    Debug.Log("Player Name: " + player.Name);
    Debug.Log("Player Email: " + player.Email);
    Debug.Log("Player Age: " + player.Age);
    
     OnDataReceived?.Invoke(playerData);
}

  1. 使用方法:
using UnityEngine;

public class GameManager : MonoBehaviour
{
    // 引用APIClient
    public APIClient apiClient;

    void Start()
    {
        // 確保apiClient已經在Inspector中賦值
        if (apiClient != null)
        {
            // 設置處理API返回數據的回調
            apiClient.OnDataReceived = HandleAPIResponse;

            // 發起POST請求並傳入玩家ID
            StartCoroutine(apiClient.PostRequest(1));
        }
        else
        {
            Debug.LogError("APIClient is not assigned in the Inspector!");
        }
    }

    // 回調函數來處理API返回的數據
    private void HandleAPIResponse(PlayerData playerData)
    {
        if (playerData != null)
        {
            // 在這裡處理API返回的數據,例如更新UI或遊戲邏輯
            Debug.Log("Player Name: " + playerData.Name);
            Debug.Log("Player Email: " + playerData.Email);
            Debug.Log("Player Age: " + playerData.Age);
        }
        else
        {
            Debug.LogError("Failed to receive player data.");
        }
    }
}

上一篇
Unity Rider - 最好用的Unity Code編輯器!
下一篇
Unity Config - 製作加密的遊戲存檔方法!
系列文
Unity黑科技揭秘:30個專業遊戲開發者必知的開發技巧25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言