- Home /
Dictionary problems
I started working on small voxel based game and I made script that generates chunks during runtime each of which has class attached to it. Said class fills array of blocks which are also rendered in the same file. However I came up with a problem while working with getting block in chosen coordinates. I made this method, but the problem is that it always jumps to else {} and never triggers the if(). What's wrong with this?
public Block GetBlock(int x, int y, int z)
{
int chunkA = x / opt.chunkSize; int chunkB = y / opt.chunkHeight; int chunkC = z / opt.chunkSize;
int a = x - chunkA * opt.chunkSize; int b = y - chunkB * opt.chunkHeight; int c = z - chunkC * opt.chunkSize;
Vector3 key = new Vector3(chunkA, chunkB, chunkC);
Block block;
if (chunkList.ContainsKey(key))
{
block = chunkList[key].GetComponent<Chunk>().block[a, b, c];
}
else
{
block = new BlockAir();
}
return block;
}
Answer by MaxGuernseyIII · Sep 27, 2017 at 05:03 AM
There are multiple possibilities.
The chunkList you're inspecting isn't the one you populate.
You're bumping up against Vector3's extreme intolerance when it comes to equals (all the floats in it must be exactly equal, which is sometimes hard to manage because float arithmetic is imprecise).
The key-generation arithmetic you've defined at the beginning of GetBlock does not line up with the key-generation arithmetic used to create the dictionary.
That's not to say there aren't other options. Those are the three I can think of immediately.
If it's #1, then the chunkList you're looking at would be empty. The solution is to make sure that you are looking at the right instance of that dictionary.
If it's #2, then the solution is to make your own key type that implements Equals and GetHashCode for three integers. This can be done really easily with a struct.
If it's #3, then the solution is to concentrate the duplicated implementations of the key-generation logic. It's easy for two redundant algorithms to be subtly out of alignment but it's impossible for the only implementation of an algorithm to be out of alignment with itself.
Thanks! It totally was that since I called the method from another class I totally forgot that it was new instance of that class rather than the instance added to the game Object.