Jump to content

Capability confusion


matthew123

Recommended Posts

I did not fully understand capabilities (specifically the capability provider). I am now facing an issue I believe has to do with an instance of my capability class lingering. 

I arrived at this conclusion by logging inside the capability class's constructor. Upon joining my single player world, the log indicates that the class was instanced. Upon leaving, then joining again, the message no longer appears. I believe this has to do with the static LazyOptional field doohickey inside this class:

public class CapabilityProvider implements ICapabilitySerializable<INBT> {

    @CapabilityInject(ITheCapability.class)
    public static Capability<ITheCapability> CAPABILITY = null;

    private static final LazyOptional<ITheCapability> lazyOptional = LazyOptional.of(TheCapability::new);

    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> capability, @Nullable Direction side) {

        // don't use the one line if statement.

        if (capability == CAPABILITY) {
            return lazyOptional.cast();
        }

        return LazyOptional.empty();
    }

    @Override
    public INBT serializeNBT() {
        return CAPABILITY.getStorage().writeNBT(CAPABILITY, lazyOptional.orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")), null);
    }

    @Override
    public void deserializeNBT(INBT nbt) {
        CAPABILITY.getStorage().readNBT(CAPABILITY, lazyOptional.orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")), null, nbt);
    }
}

That static field obviously persists and essentially turns my class into a singleton, which is not what I want. Can anyone explain the usage of LazyOptional and how to fix my implementation?

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.