Makes it possible to auto-delete a closed GUI

This commit is contained in:
Kristian Knarvik 2023-01-18 16:48:26 +01:00
parent 836c1b151e
commit 5bc251309a
2 changed files with 20 additions and 4 deletions

View File

@ -13,6 +13,17 @@ import org.bukkit.event.player.PlayerQuitEvent;
*/ */
public class GUIListener implements Listener { public class GUIListener implements Listener {
private final boolean autoDelete;
/**
* Instantiates a new GUI listener
*
* @param autoDelete <p>Whether to automatically delete closed GUIs. Useful to prevent RAM leaks</p>
*/
public GUIListener(boolean autoDelete) {
this.autoDelete = autoDelete;
}
@EventHandler @EventHandler
public void onInventoryClick(InventoryClickEvent event) { public void onInventoryClick(InventoryClickEvent event) {
HumanEntity clicker = event.getWhoClicked(); HumanEntity clicker = event.getWhoClicked();
@ -41,12 +52,12 @@ public class GUIListener implements Listener {
if (!(event.getPlayer() instanceof Player player)) { if (!(event.getPlayer() instanceof Player player)) {
return; return;
} }
GUIRegistry.closeGUI(player); GUIRegistry.closeGUI(player, autoDelete);
} }
@EventHandler @EventHandler
public void onPlayerQuit(PlayerQuitEvent event) { public void onPlayerQuit(PlayerQuitEvent event) {
GUIRegistry.closeGUI(event.getPlayer()); GUIRegistry.closeGUI(event.getPlayer(), autoDelete);
} }
} }

View File

@ -55,9 +55,10 @@ public class GUIRegistry {
/** /**
* Registers a GUI as being closed for the given player * Registers a GUI as being closed for the given player
* *
* @param player <p>The player that closed a GUI</p> * @param player <p>The player that closed a GUI</p>
* @param autoDelete <p>Whether to immediately delete the closed GUI</p>
*/ */
public static void closeGUI(Player player) { public static void closeGUI(Player player, boolean autoDelete) {
//Run the close action if an anvil GUI is used //Run the close action if an anvil GUI is used
AbstractGUI gui = getOpenGUI(player); AbstractGUI gui = getOpenGUI(player);
if (gui instanceof AnvilGUI anvilGUI) { if (gui instanceof AnvilGUI anvilGUI) {
@ -65,6 +66,10 @@ public class GUIRegistry {
} }
//Un-register the player's open GUI //Un-register the player's open GUI
openGUIs.remove(player.getUniqueId()); openGUIs.remove(player.getUniqueId());
if (gui != null && autoDelete) {
deleteGUI(gui.getUuid());
}
} }
/** /**