How to hit Api in Unity Game ||

Поділитися
Вставка
  • Опубліковано 21 жов 2024

КОМЕНТАРІ • 3

  • @IOSALive
    @IOSALive 4 місяці тому +1

    paradise _hope, This made me laugh so much! Thanks for sharing!

  • @paradise_hope
    @paradise_hope  4 місяці тому +1

    //api.cs
    using System.Collections;
    using UnityEngine;
    using UnityEngine.Networking;
    public class ApiRequest : MonoBehaviour
    {
    // URL of the API endpoint
    public string apiUrl = "jsonplaceholder.typicode.com/users";
    // Example of header key and value
    public string headerKey = "Authorization";
    public string headerValue = "Bearer your_token_here";
    void Start()
    {
    // Automatically start the API request when the scene starts
    StartCoroutine(MakeApiRequest());
    }
    // Coroutine to handle the API request
    private IEnumerator MakeApiRequest()
    {
    // Create a new UnityWebRequest
    using (UnityWebRequest webRequest = UnityWebRequest.Get(apiUrl))
    {
    // Set the request header
    webRequest.SetRequestHeader(headerKey, headerValue);
    // Send the request and wait for a response
    yield return webRequest.SendWebRequest();
    // Check for errors
    if (webRequest.result == UnityWebRequest.Result.ConnectionError ||
    webRequest.result == UnityWebRequest.Result.DataProcessingError ||
    webRequest.result == UnityWebRequest.Result.ProtocolError)
    {
    Debug.LogError("Error: " + webRequest.error);
    }
    else
    {
    // Process the response
    Debug.Log("Response: " + webRequest.downloadHandler.text);
    }
    }
    }
    }