Situation:
I'm trying to write a small controller for a key chest that spawns NPC's and only allows you to have a single NPC spawned at once. The spawned NPC needs to be spawned so that it is attacking the player (so players can safely input keys without their loot being stolen).
Attempted solution:
Code:
public static void useKey(final Player p)
{
if(hasKey(p) && p.getNPC() == null)
{
p.getPackets().sendGameMessage("You sacrifice a muddy key to the chest");
p.getInventory().deleteItem(SkeletonHorrorChest.KEY, 1);
class SkeletonKeyThread implements Runnable{
private Player player = p;
SkeletonKeyThread(Player currentPlayer){ player = currentPlayer;}
@Override
public void run() {
NPC n = new NPC(SkeletonHorrorChest.SKELEHORRORID, p, -1, true,true);
player.setNPC(n);
player.getPackets().sendGameMessage("PLAYER NPC SET TO ID");
World.addNPC(n);
player.getPackets().sendGameMessage("ADDED NPC TO WORLD");
n.setAttackedBy(player);
player.getPackets().sendGameMessage("SET ATTACKED BY NPC");
while(!n.isDead()){}
p.setNPC(null);
}
}
new Thread(new SkeletonKeyThread(p) {}).start();
}
}
Extra info:
player.get/setNPC are classes I added to player to handle the currently spawned npc, it is a simple getter/setter in the playerclass and the variable is marked as volatile. I have debugged the code with player messages and I am 100% sure that the issue lies within the loop.
I have written this in such a way that it is (supposed to) spawn a thread that stays alive until the npc dies, however what actually winds up happening is the while(!n.isDead()){} never stops for some reason. I have no idea what I am doing wrong which is why I have posted this, so any help is appreciated as well as pointers, criticism as long as its constructive and any literature you have that might help me out. Thanks for the help.