Firing Events

Discussion in 'Plugin Development' started by collielimabean, Jul 5, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    collielimabean

    Alright, I ran into a problem while making a plugin. Please note that I am a bit unfamiliar with data structures (but I'll learn them in time).

    Code:java
    1. public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
    2. {
    3. if(...)
    4. { /* excluded for space */ }
    5. ... /* more code that isn't necessary to question */
    6.  
    7. else if(args[0].equalsIgnoreCase("protect"))
    8. { protectMob(player, args); } //local var. player is a Player Object cast from sender.
    9. }
    10.  
    11. private void protectMob(Player player, args)
    12. {
    13. //tell player to right click to get entity
    14. //call new class which requires the right clicked entity here
    15. MobProtection mp = new MobProtection(player, rightClicked, args[1] /*name*/);
    16. }
    17.  
    18. //event handler
    19. @EventHandler(priority = EventPriority.HIGH)
    20. public void onRightClick(PlayerInteractEntityEvent event)
    21. {
    22. rightClicked = event.getRightClicked(); // rightClicked is a field of type Entity
    23. }
    24.  


    Before I call the function protectMob, I need the field rightClicked to be initialized (every Java programmer knows the terror of java.lang.NullPointerException). However, the user needs time to select the mob.

    My first thought was to put in while loop checking for rightClicked to be initialized, but I realized that it wasn't thread-safe - it would throw the server into an infinite loop.

    So my question is this: Is there a thread-safe way to wait for an event to fire, then execute a further block of code?
    (I do realize that my code may be written poorly and that getting my desired output may require a complete restructuring of methods).

    Okay - solved it.

    I had reorganize the methods so that the method 'protectMob' would be called in the firing of the event.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 3, 2016
Thread Status:
Not open for further replies.

Share This Page