I am using libGDX - Ashley as entity-system framework. My problem is I don't know how do I avoid having a java.lang.NullPointerException
when using Comparator<Entity>
entity comparison. There is a situation where Entity is removed from the engine, but the Comparator
is still continuing. Now how do I skip the comparing if one of the nearby is null?
@Override
public int compare(Entity nearby1, Entity nearby2) {
Vector2 ownerPos = Mapper.transform.get(owner).position;
Vector2 nearbyPos1 = Mapper.transform.get(nearby1).position; // possible null
Vector2 nearbyPos2 = Mapper.transform.get(nearby2).position; // possible null
return ...
}
When I sort the Array<Entity>
for example, using my custom comparator, it returns an error because one of the entity is null or one of the component entity is null. I don't know what to return to make the comparison skip.
boolean skip = ownerPos == null || nearbyPos1 == null || nearbyPos2 == null;
if(skip) {
return ???
}
I'm thinking of using try-catch statement to skip the sorting. But is this performance safe?
try {
array.sort(comparator);
} catch(Exception e) {
}