I am building a game. I have an array of "crystals", and I want to make it so that whenever my main character hits the crystals, it removes the crystals from the array. I already have all the code for rendering and updating, but I need to get the crystals out of the array. If I simply set it to null, by using crystal = null; it still works. How can I remove it?
If you need more information, please tell me which parts.
"The most exciting phrase to hear in science, the one that heralds new discoveries, is not 'Eureka!', but 'That's funny...' "
- Isaac Asimov
Alix Ollivier wrote:I am building a game. I have an array of "crystals", and I want to make it so that whenever my main character hits the crystals, it removes the crystals from the array. I already have all the code for rendering and updating, but I need to get the crystals out of the array. If I simply set it to null, by using crystal = null; it still works. How can I remove it?
My suggestion would be to use a List (or possibly a Map) rather than an array.
Winston
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
Alix Ollivier wrote:What are those? Built-in classes or do I have to make my own map?
Built in classes. Have a look at the java.util.List (←click) and java.util.Map docs; which are both interfaces - they will guide to the implementation classes (eg, ArrayList).
Winston
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
You are creating a new variable in the for loop, then assigning that variable to null. You are not changing the value in the array. You will need to use the array[index] syntax to set the values in the array to null.
So depending on what you need, nulling out the element may or may not work.
If you have an egg carton that holds 12 eggs, you can take an egg or two out, but the carton is still big enough to hold 12 eggs. If you look at each slot, you will occasionally come across an empty spot. That may be OK, depending on your needs.
An array, once created, never changes size. If you need to shrink your array from 12 to 10, your only option is to create a new array that is the 'correct' size, and then copy the elements into it.
Or, as others have suggested, us a different collection.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Live ordinary life in an extraordinary way. Details embedded in this tiny ad:
a bit of art, as a gift, the permaculture playing cards