Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Async REST call - where and how please?

Discussion in 'Project Tiny' started by signalan, Jan 19, 2019.

  1. signalan

    signalan

    Joined:
    Oct 5, 2018
    Posts:
    15
    Hi,
    I learned how to make a simple game Tiny, and now I'd like to make an async REST call to get some JSON data from a server like ajax call and after getting data to load a level. How to properly do it please?

    It just come to mind to do something like this:
    1. make an Entity and have the URL on it
    2. filter it in a behavior, and OnEnable make the URL call
    3. in OnUpdate look for completed call and close (disable), while loading the level that needs the JSON data

    Any example please?
     
  2. pankaj_khanduja_10

    pankaj_khanduja_10

    Joined:
    May 16, 2017
    Posts:
    5
    Hello,
    Here it is
    // Sending Request to get the Data in JSON format
    loadAsync(url: string, callback: (error?: any, jsonResponse?: any) => void): void {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onload = function () {
    var status = xhr.status;
    if (status == 200) callback(null, xhr.response);
    else callback(status);
    };
    xhr.send();
    }

    //calling loadAsync
    loadAsync("URL",(error, data) => {
    if (error) return;
    else{ console.log(data); }
    });
     
  3. pankaj_khanduja_10

    pankaj_khanduja_10

    Joined:
    May 16, 2017
    Posts:
    5
    Hello ,
    Sure, i will help you out by writing code .
    Before moving on, please clear few points-
    In the first scene, you want to get 10 numbers from the server so my question is all 10 numbers will be returned in json format in single request?