Sound enum and others in multiple versions

Jun 8, 2017
Sound enum and others in multiple versions
  • Sound enum and others in multiple versions

    How to use enums that change such as Sound in a multi-version plugin



    If you want to play a sound to a player in a plugin, it's very simple! You just have to do
    Code (Text):

    player.playSound(player.getEyeLocation(), Sound.BLOCK_NOTE_PLING, 1, 1);
     
    So what's wrong with that? Well, in 1.9 the sound names in the Sound enum were changed to be more like what you would use in the /playsound command. You can find the names here:
    1.9
    Before 1.9

    Now, any plugin that was made for 1.7/1.8 no longer work with 1.9! So.. How do you make a 1.9 plugin backwards compatible now? Well, you can make an if statement for version number... let's try that!
    Code (Text):

    if (Bukkit.getVersion().contains("1.9")) {
         player.playSound(player.getEyeLocation(), Sound.BLOCK_NOTE_PLING, 1, 1);
    } else {
         player.playSound(player.getEyeLocation(), Sound.NOTE_PLING, 1, 1);
    }
     
    Well, sadly that won't work either. Why? Because Sound.NOTE_PLING doesn't exist in 1.9, and you are using 1.9 as a library! And don't try switching the library version, then the first one won't work! So what do you do, use both as a library at the same time? Well, no. That would be silly. Instead, you do this:
    Code (Text):

    if (Bukkit.getVersion().contains("1.9")) {
         player.playSound(player.getEyeLocation(), Sound.valueOf("BLOCK_NOTE_PLING"), 1, 1);
    } else {
         player.playSound(player.getEyeLocation(), Sound.valueOf("NOTE_PLING"), 1, 1);
    }
     
    Now it will work! You can make it a one-liner, sacrificing readability a bit, like this:
    Code (Text):

    player.playSound(player.getEyeLocation(), Sound.valueOf(Bukkit.getVersion().contains("1.9") ? "BLOCK_NOTE_PLING" : "NOTE_PLING"), 1, 1);
     
    If you're making something that uses sounds a lot you could even make a util method that does something like this:
    Code (Text):

    public static String getPre1_9Name(Sound sound) {
         switch (sound) {
              case BLOCK_NOTE_PLING: return "NOTE_PLING";
              case ENTITY_ITEM_BREAK: return "ITEM_BREAK";
         }
    }
     
    etc.

    This simple trick can open your plugins up to the larger audience of more versions while still having those awesome sound effects!
  • Loading...
  • Loading...