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.
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.
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.
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
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.
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.
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?
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.
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.