Parse string by X amount

Hey all,
I'm working on a system of generating a grid map of a fixed size based on a string. For simplicity, let's just say it's a 3x3 grid. So what I'm trying to make is a string like "FHFTFGFJHDFBAFAHAY" the idea being that every 2 characters make up a single reference that will spawn the according tile on thr grid. So in the above example: FH means it's a field that spawns at 1,1 FT means a mountain spawns at 1,2 and FG means a lake will spawn at 1,3 and so on.

So my question is: how do I parse a string for every other character?

Strings are arrays of characters. They have an indexer, in fact, that returns the character at each index. So one way is to just treat them like arrays and iterate through them:

string someString = "String";
for (int i = 0; i < someString.Length; i++)
   char c = someString[i];

The string class also has a number of methods for getting smaller pieces of the string at the same time. Though do note that working with strings like this will allocate a ton.

a way to get two characters in a string would be

string someString = "String";
for (int i = 0; i < someString.Length; i+2)
   string c = someString[i]+someString[i+1];

But is going with a string the best way? Where does the string come from, how is it generated?

That makes sense, I'll likely need to use a more efficient system in the future. But that's a good starting place!

Oh that makes sense! And would be pretty easy to implement. Thanks!

As for it being the best way, probably not. I'll be generating the string a little later (pretty much just a for loop that generates 2 characters for every tile, based on what the tile should be) that will be used for the map.

An array of bytes could be more straight forward.

Depends how many different types of tiles you have. I'm working on a tile-based game as well, and opted to use ushort as the numerical ID's for different tile types. And then a 16 * 16 (256) array of these can be used to generate the necessary data for a chunk.

Then a singleton scriptable object with a lookup table (dictionary serialised with Odin) can be used to convert these ID's into the actual scriptable objects that define the tiles.

Oh wow, that sounds way more efficient!

I'm not 100% sure on how big the tile array will be, still toying around with that, but probably in the neighborhood of 50ish to 100ish.

Maybe I'll look into ushorts instead. I'm not too familiar with them, so probably something I should learn about.

I more so mean how many different types of tiles there'll be. As you'll need a data type can represent enough different kinds of tiles. A byte will give you a capacity of 256 different types. A ushort - which is just halfway between a byte and a uint - gives you 65,535 different types, which is enough for most games.

1 Like