2
\$\begingroup\$

So I'm trying to make an efficient game where there is a grid system and every grid has a number that is able to identify what kind of block is located there. This lets me just have an array of numbers rather than an array of block-objects.

But now here is my problem, when I want to call a method from one of block classes, I only have a number to reference it. And I don't want to have a giant switch block to try and determine which block it is.

So in short, how can I get an specific int to reference a certain class without a massive if chain or switch block?

I believe Minecraft does something like this. All the blocks are saved in memory as a number, and then when the game wants to draw or call a method on one of the blocks, it uses the number at that location to reference to block to call the method. How does it do this?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You just need a small, constant array of block objects. Your block IDs will then be indices into this array.

Alternatively, you could use something like a HashMap to map IDs to blocks. This is generally slower and consumes more memory than a simple array, but it does have the advantage of not requiring your IDs to be contiguous, which might be useful in some situations.

\$\endgroup\$
1
  • \$\begingroup\$ I actually thought of using a HashMap initially, but I guess I was just being too stupid to figure out how to make it work. But now that I actually but some thought into it, I actually figured it out lol I must have had a brain fart moment \$\endgroup\$ Dec 21, 2015 at 2:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .