Incorrect use of `LazyOptional` in versions prior to 1.21
solonovamax opened this issue · 4 comments
In versions prior to 1.21, you are incorrectly using LazyOptional
.
If you look at the update
method of HordeEventHandler
, the code looks roughly like this:
@SubscribeEvent(priority=EventPriority.LOWEST)
public void update(LivingTickEvent event) {
ServerPlayer player = HordeSpawn.getHordePlayer(event.getEntity());
if (player == null) return;
HordeSpawn cap = event.getEntity().getCapability(HordesCapabilities.HORDESPAWN).orElseGet(null);
// ...
}
The issue is with the code orElseGet(null)
. As stated by the javadocs for LazyOptional#orElseGet(NonNullSupplier)
:
Throws:
NullPointerException - If other is null and this LazyOptional is non-empty
I'm assuming that "is non-empty" is a typo and they intended to write "is empty".
As, a NullPointerException
is thrown if the HordesCapabilities.HORDESPAWN
capability is not present.
The correct solution to this would be one of two things:
- Use
LazyOptional#orElse(T)
. This returns the value passed to it if theLazyOptional
is empty. - Use
LazyOptional#isPresent()
, as done previously:
This is the cause of several different crashes, such as:
HordeSpawn::getPlayer should return null if it isn't present anyway, unless there's something strange going on incorrect use of LazyOptional shouldn't be the cause of this issue. That is unless something weird is happening to the capability inbetween uses.
As I'm playing on 1.18.2, the only fix is to revert to version 1.2.3, where the issue was not present.
HordeSpawn::getPlayer should return null if it isn't present anyway, unless there's something strange going on incorrect use of LazyOptional shouldn't be the cause of this issue. That is unless something weird is happening to the capability inbetween uses.
yeah I realized that after looking at it some more, but didn't make a comment about it. unsure why it's hitting that codepath.