From ce334cb3fd66bc8ead48c2a8df15cb2f15127fc7 Mon Sep 17 00:00:00 2001 From: Will FP Date: Mon, 23 Dec 2024 11:34:32 +0000 Subject: [PATCH] Added cross-version sound fix --- .../java/com/willfp/eco/util/SoundUtils.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 eco-api/src/main/java/com/willfp/eco/util/SoundUtils.java diff --git a/eco-api/src/main/java/com/willfp/eco/util/SoundUtils.java b/eco-api/src/main/java/com/willfp/eco/util/SoundUtils.java new file mode 100644 index 00000000..25ece169 --- /dev/null +++ b/eco-api/src/main/java/com/willfp/eco/util/SoundUtils.java @@ -0,0 +1,50 @@ +package com.willfp.eco.util; + +import com.willfp.eco.core.Prerequisite; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.Sound; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.reflect.Field; + +/** + * Utilities / API methods for sounds. + */ +public final class SoundUtils { + /** + * Get a sound in a version-compatible way. + * + * @param name The name of the sound, case-insensitive. + * @return The sound, or null if not found. + */ + @Nullable + public static Sound getSound(@NotNull final String name) { + if (!Prerequisite.HAS_1_21_3.isMet()) { + try { + return Sound.valueOf(name.toUpperCase()); + } catch (IllegalArgumentException e) { + return null; + } + } + + // First try from registry (preferred) + Sound fromRegistry = Registry.SOUNDS.get(NamespacedKey.minecraft(name.toLowerCase())); + if (fromRegistry != null) { + return fromRegistry; + } + + // Next try using reflection (for legacy enum names) + try { + Field field = Sound.class.getDeclaredField(name.toUpperCase()); + return (Sound) field.get(null); + } catch (ReflectiveOperationException e) { + return null; + } + } + + private SoundUtils() { + throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); + } +}