I’m attempting to create a random 2D tile-based terrain generator in C#.
What i want it to do is have a list of tiles, each tile having a float value representing it’s percentage to spawn (so, a float value from 0 to 1).
Currently I make the list of percentage manually, which also means I can sort them.
In this case I sorted the array holding the percentages from highest at the back (the lowest index) and lowest at the front (highest index).
My current code works good if the array contains 2 items, with different percentages.
If I add more values to the list or make the percentages on one or more equal it will also fail.
These are all my variables related to the generation :
[SerializeField] private List<GameObject> m_tileList = new List<GameObject>();
private GameObject[,] m_worldTiles;
private const float M_TILESIZE = 2.0f;
private List<KeyValuePair<string, float>> m_chanceList = new List<KeyValuePair<string, float>> // These should together become 1, and none of them can be the same amount??
{
MakePair("Grass", 0.5f),
MakePair("Dirt_Road", 0.5f),
};
And this is the function which should generate the tiles :
public void GenerateWorld(int xSize, int ySize)
{
m_worldTiles = new GameObject[xSize, ySize];
for (int x = 0; x < xSize; x++)
{
for (int y = 0; y < ySize; y++)
{
for (int i = 0; i < m_chanceList.Count; i++)
{
float val = Random.value; // First I generate a random percentage (0 - 1).
try // The reason I use a try/catch here is because if the chance list has no next element this will crash.
{
if (m_chanceList[i + 1].Value < val) // Here I check the next element and see if the percentage that we generated randomly is less than the next one, cause that means we should be selecting the i tile in the list. I believe this is the reason it only works with two and why it doesn't work when the chance list has two or more equal values.
{
// And then we just do the spawning of the tile.
GameObject instantiated = GameObject.Instantiate(m_tileList*);*
instantiated.transform.position = new Vector3(x * M_TILESIZE, y * M_TILESIZE, 0);
m_worldTiles[x, y] = instantiated;
}
}
catch
{
}
}
}
}
}
Sorry if this makes no sense, comment if it doesn’t and I’ll try explaining again.
—
Here’s another explanation of what I want to achieve :
What I want to do is have a list full of percentages, and that percentage representing a tile.
So, if I have a value in the list it would be ****
So if the list looks something like this :
- Grass Tile, 0.5
- Dirt Tile, 0.5
- Stone Tile, 0.2
- Gold Tile, 0.0001
It should have a 50% chance to spawn a grass tile, 50% chance to spawn a dirt tile, 20% chance to spawn a stone tile, and a 0.01% chance of spawning a gold tile.