ashley icon indicating copy to clipboard operation
ashley copied to clipboard

What is the proper way of checking if the entity is already removed?

Open ronjunevaldoz opened this issue 9 years ago • 4 comments

EntityListener handles when the entity is added or removed. My problem is when I remove the entity from the engine, while this entity is being used as Component owner, it cause a java.lang.NullPointerException. I wonder what method to use to check if entity is already removed from the engine.

For example:

public class PoliceComponent implements Component {
    public Entity criminal;
}

engine.removeEntity(entity)

PoliceComponent police ...
Vector2 criminalPos = Mapper.transform.get(police.criminal).position; 
// Now this line will cause an error

Question : is there a method like this to check for entity existence? or something better safer to remove entity while is in use.

    if (engine.hasEntity(entity)) {
          // exists
    }

ronjunevaldoz avatar Sep 25 '16 15:09 ronjunevaldoz

You should probably only be iterating over entities within a given Family (usually using some sort of EntitySystem), rather than retaining references to individual entities.

It's slow (O(n)) but you can also say engine.getEntities().contains(entity), but again, I wouldn't recommend that.

nanodeath avatar Sep 26 '16 17:09 nanodeath

Not sure if I understand your problem correctly, but entity.isScheduledForRemoval() might be what you are looking for.

Lusito avatar Sep 30 '16 00:09 Lusito

Didn't realize I was using an older version, but in 1.7.0, scheduledForRemoval gets reset back to false when the entity is actually removed. 1.7.1 appears to have changed this behavior. So if you're using 1.7.1 or later, isScheduledForRemoval might work fine.

nanodeath avatar Sep 30 '16 03:09 nanodeath

@Lusito @nanodeath

Another example because I am not sure what I'm doing I need someone to confirm this.

Assume that I have an array of visions and I want it to be sorted using a comparator, suddenly a vision is removed and then the Comparator<Entity> null argument exception will returned. So before sorting I need it to be removed first so I could avoid null argument exception inside the compare method.

Ex1:

Array<Entity> observerVisions = vision.get(observer);
for (Entity vision: observerVisions) {
  if(!observables.contains(vision, true)) {
      removeFromVision(observer, vision);
   }
}

assume vision is already removed from the engine, but still in the visions, so this will be changed to?

for (Entity vision: observerVisions) {
  if(vision.isShceduledForRemoval()) {
      removeFromVision(observer, vision);
   }
}

Ex2

public int compare(Entity o1, Entity o2) {
      if(o1.isScheduledForRemoval() || o2.isScheduledForRemoval()) {
         return ??? // don't know what to return
      }  
}

visions.get(owner).sort(comparator);

ronjunevaldoz avatar Oct 01 '16 05:10 ronjunevaldoz