You can use a filter:
public static NPC getClosestAliveNotUnderAttackForNameAndActionInArea(
Script script, String name, String action, Area area) {
NPC closest = null;
double lowest = Double.MAX_VALUE;
for (NPC npc : script.getNpcs().getAll()) {
if (npc != null && npc.exists() && npc.getHealth() > 0
&& !npc.isUnderAttack()) {
final String npcName = npc.getName();
final List<String> actions = Arrays.asList(npc.getDefinition()
.getActions());
final double d = npc.getPosition()
.distance(script.myPosition());
if (npcName.equalsIgnoreCase(name) && actions.contains(action)
&& d < lowest && area.contains(npc)) {
closest = npc;
lowest = d;
}
}
}
return closest;
}
Stick that method in your code, then define your cow as:
NPC cow = this.getClosestAliveNotUnderAttackForNameAndActionInArea(this, "Cow", "Attack", COW_AREA);
//where cow area is defined as eviltwin mentioned
Otherwise what twin said works, although the messagelistener isn't 100% reliable/clean it works too.
Apaec