How to get SoundType from string?

I’m using

Optional<SoundType> sound = game.getRegistry().getType(SoundType.class, i[0]);

Where i[0] is any possible string. The problem is even when I give it a correct SoundType name it still doesn’t return with a SoundType.

This is the File

Can you paste the result of p.sendMessage(Text.of("Sound: " + i[0] + ", Volume: " + i[1] + ", Pitch: " + i[2])); ?


The fact that it’s returning that means the Optional SoundType isn’t present, even though it should be.

No, it shouldn’t be. You’ve not passed a valid ID, you’ve passed the field name. IDs in Sponge that refer to vanilla elements start with minecraft:

Using the magic of Reflection, I’ve gotten minecraft to spit out the Sponge field names and respective IDs. I’ve included the code snippet I used to generate the list.

1 Like

Thank you! I just put all those into a HashMap and it works perfectly!


I seriously DO NOT suggest you do that. The code was for illustrative purposes only to show you how I got the results out, and I feel like you don’t actually understand what it does.

You’ve created a number of problems here:

  • Server owners can’t use any modded sounds, that file will only ever contain the Vanilla sounds.
  • Reflection (what I used to get the field names) is slow. Very slow. I use it a lot in Nucleus, but I mostly limit its use to startup and try to cache everything that I get out of it. I spent a lot of time minimising the impact of it. You’re running an expensive operation, followed by creating a map each time, only to then pluck one value out of it.
  • There are other unnecessary operations:
  • sort in stream - you don’t need to do that - you don’t care what order the data is in. In fact, once you put the data in the HashMap, it’s unsorted again.
  • setAccessible(true) actually is not needed, because I realised after I posted the code that the fields are accessible anyway.
  • If the names of the field change (and they have done in the past, from API 4 to 5, for example), then your server owners placeholders potentially break. You should be providing continuity and not relying on Sponge to stay stable, especially as it’s still maturing.

I simply wanted to show you what the IDs were, and in the interests of transparency, included the code to show you how I generated it. I would seriously suggest that you develop a better way of doing this (or, at the very least, cache the reflection call), because I don’t think what you’re doing now is good for your plugin or server owners in the long run.

Yes, I thought about all of that minutes after posting that fix. What I’m going to do instead is just ask for the ID instead of the enum name.
This should allow for modded sounds too, right? If they just use the mod id.

Edit it works! :slight_smile: Commit

1 Like