I'm trying to select certain objects from an Array containing all my game objects inside my render method. Because It is inside my render method, I'm trying to avoid the garbage collector by only using member variables. My goal is to put in my tmpRenderArray GameObjects that are instances of Renderable. I then need to sort theses objects and render them.
Here's my code:
private Array<GameObject> gameObjects = new Array<>();
private Array<Renderable> tmpRenderArray = new Array<>();
public void render(float delta)
Gdx.gl.glClearColor(1f, 0.7f, 0.7f, 1f);
int i = 0;
for(GameObject object : gameObjects)
if(object instanceof Renderable)
//PRIORITY_COMPARATOR = (a, b) -> Float.compare(a.getPriority(), b.getPriority());
for(; i-- > 0; )
tmpRenderArray.items[i].render(); //<-- That line
Exception in thread "LWJGL Application" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lme.winter.project2d.Renderable;
It states in the documentation of Array that you cannot access
items if you did not use the Array constructor that specifies the class explicitly. This is because generic types are stripped at runtime by Java, so the array doesn't know the type of its objects that you access from
items. LibGDX Array provides access to stuff under the hood that you can easily misuse, I suppose so you can highly optimize code if you need to.
and it should work fine, except for the IndexOutOfBoundsException on the first element from your
i being one too high (see below).
Original answer--these bugs were not the source of the CCE
Your bugs are that you don't clear your temp array, and that your
i is one bigger than it should be due to the
i++ in the upper for loop. This object is not null, but some left over object from a previous frame. You need to start
-1 and use
++i instead of
i++. Or decrement by 1 before the second loop.
That said, some of your code is a bit convoluted. You could simplify it like this:
Gdx.gl.glClearColor(1f, 0.7f, 0.7f, 1f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.setProjectionMatrix(camera.combined); batch.begin(); tmpRenderArray.clear(); for(Renderable object : gameObjects) tmpRenderArray.add(object); tmpRenderArray.sort(Renderable.PRIORITY_COMPARATOR); //invert this comparator //PRIORITY_COMPARATOR = (b, a) -> Float.compare(b.getPriority(), a.getPriority()); for(Renderable renderable : tmpRenderArray) renderable.render(); batch.end(); //...