How can I remove an array item?

Ok, so that question was sort of broad.

I want to ask a series of random questions. I was thinking about storing my questions in an array.

When following questions are asked, how can I remove the previously asked questions from the array so the same question isn’t asked again?

Or, is there a better way to handle this? Should I be using a ?

Arrays are immutable in size. Yes, use a List() instance.

Traditionally one just shuffles a collection then steps through it in steady order from beginning to end. That gets you out of “removing” anything. When you reach the end, just reshuffle and continue.

1 Like

Ok. Thank You.

Yes. Arrays are helpful if you need to read/write a lot of data as they do have higher performance, but a List is still pretty fast while handling the more annoying details for you like adding and deleting elements. Here’s an article on the performance difference with benchmarks. It’s a bit old but it’s still applicable.

https://www.jacksondunstan.com/articles/3058

1 Like

This is sort of part of this same post, since it’s the first question I’ll be asking users. So, instead of posting another post, I’ll ask it here:

I need a location select for my users to choose their location (city, state - in the US for now). I can’t ever find a location select script online. Do I really have to manually type up 19,495 cities and 50 states? It would take a team, a month to do that. I can’t imagine game developers having to sit there for weeks or longer just to get a location select on their game.

I did begin doing that. Instead of typing them up in code, which would require typing extra characters, I made it simple by doing this:

[SerializeField] private string[] states;

and typing them in the inspector.

This way, I would also need 50 variables for each state individually, so I can associate each state with each city. I want the city drop down to populate based on the state dropdown they select. But, it seems like there should be a much easier way to do this. Like a script that’s already been completed. Unfortunately, the asset store doesn’t have one.

Have you considered to use a web service such as https://countrystatecity.in/ to fetch this data?

1 Like

Didn’t know about that. Thanks for the resource. When I Googled for it, I couldn’t find anything like that.

This:

var headers = new Headers();
headers.append("X-CSCAPI-KEY", "API_KEY");

var requestOptions = {
  method: 'GET',
  headers: headers,
  redirect: 'follow'
};

// Pass Country Code -- Eg: Country Code : IN
fetch("https://api.countrystatecity.in/v1/countries/IN/states", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

Looks like React.

Do they have C# API?

It looks like that’s what they have lol - I’m going to have to figure out how to use React within Unity, correct? I tried figuring this out with PHP because I’m good with PHP, and the process to get PHP working within Unity seemed very complex. Guess I have more education ahead of me lol

React has nothing to do with Unity.

Like React, PHP has absolutely nothing to do with Unity.

You need to learn how to query a basic REST API.

Look for tutorials on querying a basic REST API.

In Unity, the easiest will likely be with the UnityWebRequest class.

But get the API working from the command line FIRST:

Networking, UnityWebRequest, WWW, Postman, curl, WebAPI, etc:

https://discussions.unity.com/t/831681/2

https://discussions.unity.com/t/837672/2

And setting up a proxy can be very helpful too, in order to compare traffic:

https://support.unity.com/hc/en-us/articles/115002917683-Using-Charles-Proxy-with-Unity

I’m aware React and PHP have nothing to do with Unity, but there are ways of using PHP in Unity, the process seemed difficult. Writing the PHP code is simple, but then there was some process of writing a c# script that used the PHP file. Anyways, thanks for the guidance. I will look into REST API, which I have used in other programming languages before, so hopefully some of it will seem familiar.

Oh, I remember now. I used REST API when learning React. lol When you mentioned UnityWebRequest, I was like, why does WebRequest sound familiar? I learned React 8 years ago in college. Haven’t used it since. I’ve always preferred PHP for building websites, even though React and Node are arguably better for web development.

I’ve never really been good with APIs. It’s sort of my weakest point in programming. Guess I better get to educating myself. :slight_smile:

Why?!! What data problem are you actually trying to solve here?

This post started out with a simple question about selectively removing data from a collection and now you’re talking about integrating PHP with Unity, which makes no sense whatsoever.

Sorry, I kind of was just using an example how that API looks like React. Then, you said React had nothing to do with Unity. I was just explaining I know that, but you can implement other languages within Unity. I was just affirming that I know they have nothing to do with Unity.

However, in this case from what I’m discovering, you do have to implement either JavaScript, PHP, Axios, Dart, JQuery, or Go within Unity since those are the only options offered by https://countrystatecity.in.

So, before I go on my learning journey, I’m assuming, I will have to use a JavaScript, PHP, Axios, Dart, JQuery, or Go file and then write a C# script to use one of those files to access the API.

Of those, I am most familiar with JavaScript and PHP, but Axios is actually where I learned using APIs (years ago).

NO!!

That’s what someone else (may have) used to write that website.

Use UnityWebRequest from C# within Unity.

That’s it.

All you have to do is make a GET web-request via Unity/C#. The web-service then sends a json response back that contains what you’re looking for.

When you look at the examples on that website, you will see that they’re also simply sending GET requests.

2 Likes

I’m so confused. How can you use non-C# code in C#?

This, according to the documentation:

var headers = new Headers();
headers.append("X-CSCAPI-KEY", "API_KEY");
var requestOptions = {
  method: 'GET',
  headers: headers,
  redirect: 'follow'
};
// Pass Country Code -- Eg: Country Code : IN
fetch("https://api.countrystatecity.in/v1/countries/IN/states", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

Does not look like C# code.
If I use a UnityWebRequest, don’t I need the code that GETS the data?

According to UnityWebRequest documentation, there’s no place to insert an API Key. Just an url. So, how can I get use the API Key, without the code where you put the API Key?

That’s correct, but all the code is really doing it setting up a GET web-request. You can do the same in Unity/C#.

You can create a UnityWebRequest, you can set up the header to fill in the key, etc.

1 Like

What you do not understand is that the concept of a HTTP request does not belong to any of the languages you mentioned. Almost all programming languages have socket or http request support. So your doing the same thing, just in a different language. Are you even familiar with http? HTTP itself is a text-based network protocol for transfering “hyper text” (Hyper Text Transfer Protocol). It’s the basis of the www and can be used to send and receive much more than “hyper text”.

The UnityWebRequest represents an http client. So you can send a request to any http server. The documentation actually documents how their HTTP API looks like. The examples they provided are just that, examples in various languages. Technically you don’t need any of those examples to use that API, but examples of course makes it easier for developers to understand how it works. They just included some examples of the most common web programming languages since that’s where you would use such a service most of the time.

Technically this should be enough to get the country list:

using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;

public class CountryStatecity : MonoBehaviour
{
    async void Start()
    {
        // Test it here
        var res = await CountryStatecityAPI.GetAllCountries();
        if (res != null)
        {
            foreach (var c in res.countries)
            {
                Debug.Log("C:" + c);
            }
        }
    }
}

public static class CountryStatecityAPI
{
    static string allCountries = "https://api.countrystatecity.in/v1/countries";
    static string apiKey = "YOUR API KEY";

    [System.Serializable]
    public class Countries
    {
        public List<Country> countries;
    }
    [System.Serializable]
    public class Country
    {
        public int id;
        public string name;
        public string iso2;
        public override string ToString()
        {
            return $"{id} - {name} - {iso2}";
        }
    }
    public static async Task<Countries> GetAllCountries()
    {
        var req = UnityWebRequest.Get(allCountries);
        req.SetRequestHeader("X-CSCAPI-KEY", apiKey);
        await req.SendWebRequest();
        if (req.responseCode != 200)
        {
            Debug.LogError("API request failed: " + req.error);
            return null;
        }
        string json = "{\"countries\":" + req.downloadHandler.text + "}";
        return JsonUtility.FromJson<Countries>(json);
    }
}

Of course other API requests would need different classes to represent the returned data. Another solution may be to use my SimplyJSON or any other JSON parser that can map the json to generic data structures so you would not need to create individual classes for each request you may need. Though if you only need a handful of endpoints, this method should work.

Currently I don’t have an API key (but I have requested one, though it seems it takes some time) so I can’t test the code. Though according to the documentation that should be enough. Currently I get a “HTTP/1.1 401 Unauthorized” when I try my code. If you have an API key, you can try it with your key.

3 Likes

Note that this website’s demo actually pulls it’s information out of this github repository. There are several json files in the root of this repository like the countries.json. Note the License of that database. Currently I can’t be bothered reading the whole license. However if you plan copying parts of it, make sure you read the license first.