Jump to content

Help with enderchest type item


ND0322

Recommended Posts

I am looking to make a container that is opened through an item and has a seperate inventory for each player like an enderchest. I have created a capability to do this however it does not work. Here is the code:

 

ItemStackHandler:

public class CharmBagItemStackHandler extends ItemStackHandler implements CharmBagItemHandler {
	public int size;
	public CharmBagItemStackHandler(int size) {
		super(size);
	}
	
	public CharmBagItemStackHandler() {
		super(9);
	}

	public void copyFrom(CharmBagItemStackHandler source) {
		this.size = source.size;
		
	}
	
	

}

Capability provider(the code is a little messy):

public class CharmBagProvider implements ICapabilityProvider, INBTSerializable<CompoundTag>{
	public static Capability<CharmBagItemStackHandler> Handler = CapabilityManager.get(new CapabilityToken<>(){});
	
	private CharmBagItemStackHandler inventory = new CharmBagItemStackHandler(9);
	private Player player;
	
	public static CharmBagItemStackHandler CHARMBAG = null;
	private LazyOptional<CharmBagItemHandler> lazyOptional = LazyOptional.of(() -> inventory);
	
	
	@Nonnull
    private CharmBagItemStackHandler createHandler() {
        if (CHARMBAG == null) {
            CHARMBAG = new CharmBagItemStackHandler();
        }
        return CHARMBAG;
    }

	@Override
	public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
		
		
		if (cap == Handler) {
	            lazyOptional.cast();
	        }
	        return LazyOptional.empty();
	      
	}

	@Override
	public CompoundTag serializeNBT() {
		return inventory.serializeNBT();
	}

	@Override
	public void deserializeNBT(CompoundTag nbt) {
		inventory.deserializeNBT(nbt);
		
	}

	


}

Container:

public class CharmsBagContainer extends AbstractContainerMenu{
	private final ItemStack charmBag;
    private final Level level;
    
    
    
    // Client Constructor
    public CharmsBagContainer(int id, Inventory playerInv) {
    	this(id, playerInv, playerInv.player.getMainHandItem());
    }

    // Server constructor
    public CharmsBagContainer(int id, Inventory inventory, ItemStack item) {
        super(ContainerInit.CHARM_CONTAINER.get(), id);
       
        this.level = inventory.player.level;
        this.charmBag = item;
        Player player = inventory.player;     
      
        
        
       System.out.println(player.getCapability(CharmBagProvider.Handler).isPresent());
       player.getCapability(CharmBagProvider.Handler).ifPresent(handler -> {
            for(int i = 0; i < 3; ++i) {
                for(int j = 0; j < 3; ++j) {
                    this.addSlot(new SlotItemHandler(handler, j + i * 3, 44 + j * 18, 16 + i * 18));
                }
            }
        });
     
        

      
        
        this.addPlayerHotbar(inventory);
        this.addPlayerInventory(inventory);
      
        
        
    }
    
    private void addPlayerInventory(Inventory inv){
        for(int i = 0; i < 3; ++i) {
            for(int j = 0; j < 9; ++j) {
                this.addSlot(new Slot(inv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
            }
        }
    }
    

    private void addPlayerHotbar(Inventory inv){
        for(int k = 0; k < 9; ++k) {
            this.addSlot(new Slot(inv, k, 8 + k * 18, 142));
        }
    }

   
    @Override
    public ItemStack quickMoveStack(Player pPlayer, int pIndex) {
        ItemStack toReturn = ItemStack.EMPTY;
        Slot slot = this.getSlot(pIndex);
        if(slot != null && slot.hasItem()){
            ItemStack stack = slot.getItem();
            toReturn = stack.copy();
            if(pIndex < 9){
                if(!this.moveItemStackTo(stack, 9, this.slots.size(), true)){
                    return ItemStack.EMPTY;
                }
            }else if(!this.moveItemStackTo(stack, 0, 9, false)){
                return ItemStack.EMPTY;
            }

            if(!stack.isEmpty()){
                slot.set(ItemStack.EMPTY);
            }else{
                slot.setChanged();
            }
        }
        return toReturn;
    }
   
	@Override
	public boolean stillValid(Player player) {
		
		return player.getMainHandItem().is(this.charmBag.getItem());
	}

EventHandler:

@SubscribeEvent
	public static void onAttachCapabilitiesPlayer(AttachCapabilitiesEvent<Entity> event){
        if (event.getObject() instanceof Player) {
            if (!event.getObject().getCapability(MaxHealthProvider.MAX_HEALTH_CHANGER).isPresent()) {
                // The player does not already have this capability so we need to add the capability provider here
                event.addCapability(new ResourceLocation(truffleMod.MOD_ID, "max_health"), new MaxHealthProvider());
            }
        }
    }
	@SubscribeEvent
	public static void onPlayerCloned(PlayerEvent.Clone event) {
        if (event.isWasDeath()) {
            // We need to copyFrom the capabilities
            event.getOriginal().getCapability(MaxHealthProvider.MAX_HEALTH_CHANGER).ifPresent(oldStore -> {
                event.getPlayer().getCapability(MaxHealthProvider.MAX_HEALTH_CHANGER).ifPresent(newStore -> {
                    newStore.copyFrom(oldStore);
                });
            });
        }
    }
    
	@SubscribeEvent
	public static void onRegisterCapabilities(RegisterCapabilitiesEvent event) {
        event.register(MaxHealth.class);
    }
}

My issue is probably with attaching the capability as I print to show if the player has the capability and it prints false.

Link to comment
Share on other sites

@SubscribeEvent
	public static void onAttachCapabilitiesPlayer(AttachCapabilitiesEvent<Entity> event){
		
		
        if (event.getObject() instanceof Player) {
        	
        	 if (!event.getObject().getCapability(CharmBagProvider.Handler).isPresent()) {
        	
                event.addCapability(new ResourceLocation(truffleMod.MOD_ID, "charm_bag_cap"), new CharmBagProvider());
                System.out.println("added");
            }
        	System.out.println("eventRan");
        }
    }

I have put two prints to check that the event is called and both are called

Edited by ND0322
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.



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • https://gist.github.com/it-is-allie/29645c4fb5c7131ad30181769a37d12f There is my latest crash report. I've spent probably 5 hours messing with modpacks and have gotten it almost complete but it then randomly crashes before loading all the mods? I'm not even sure. if anyone  could help it would be greatly appreciated.   
    • Hi, Forge refuses to recognize the mods "moonlight" and "enhancedcelestial" in my friend's modpack for essential, we have double checked that the modpack we're using has both those mods, and it still won't recognize, saying I don't have them. If I try to manually add these mods into my game, it gives me the "Unexpected custom data from client" error. I am stuck in a loop here. -- Unexpected custom data from client Missing required datapack registries: moonlight:soft_fluids, enchancedcelestials:lunar/event, enhancedcelestials:lunar/dimension_settings, moonlight:map_markers -- Logs https://pastebin.com/rvFnk4n3
    • Good afternoon, I have a problem with the minecraft launcher, when trying to open a version with forge it does not open the minecraft and the launcher gives me an error code 1, this passes me from version 1.17 onwards and without having any mod installed.   [29jun.2024 18:08:14.073] [main/INFO] [cpw.mods.modlauncher.Launcher/MODLAUNCHER]: ModLauncher running: args [--username, MarkitoPlex, --version, 1.20.1-forge-47.3.1, --gameDir, C:\Users\Marco Antonio RL\AppData\Roaming\.minecraft, --assetsDir, C:\Users\Marco Antonio RL\AppData\Roaming\.minecraft\assets, --assetIndex, 5, --uuid, 4768b6d7e7fa48f58946cbe18989d2e3, --accessToken, ????????, --clientId, ZmEwYTkyM2YtZTU2YS00NTVlLWE4NTgtYjY0MWI5YzFhODc1, --xuid, 2535453534635465, --userType, msa, --versionType, release, --quickPlayPath, C:\Users\Marco Antonio RL\AppData\Roaming\.minecraft\quickPlay\java\1719706091955.json, --launchTarget, forgeclient, --fml.forgeVersion, 47.3.1, --fml.mcVersion, 1.20.1, --fml.forgeGroup, net.minecraftforge, --fml.mcpVersion, 20230612.114412] [29jun.2024 18:08:14.077] [main/INFO] [cpw.mods.modlauncher.Launcher/MODLAUNCHER]: ModLauncher 10.0.9+10.0.9+main.dcd20f30 starting: java version 17.0.8 by Microsoft; OS Windows 11 arch amd64 version 10.0 [29jun.2024 18:08:14.178] [main/WARN] [net.minecraftforge.fml.loading.FMLConfig/CORE]: Configuration file C:\Users\Marco Antonio RL\AppData\Roaming\.minecraft\config\fml.toml is not correct. Correcting [29jun.2024 18:08:14.179] [main/INFO] [net.minecraftforge.fml.loading.FMLConfig/CORE]: Incorrect key [earlyWindowShowCPU] was corrected from null to false [29jun.2024 18:08:14.196] [main/INFO] [net.minecraftforge.fml.loading.ImmediateWindowHandler/]: Loading ImmediateWindowProvider fmlearlywindow [29jun.2024 18:08:14.341] [main/INFO] [EARLYDISPLAY/]: Trying GL version 4.6    
    • Hi, I was wondering how to make a "screenspace texture" like the background of the end portal (not including the moving stars). This is an example of what I want:  I have taken a look at the vanilla shader files, but I don't know how to use the effect for myself. Any help would be great,
  • Topics

  • Who's Online (See full list)

    • There are no registered users currently online
×
×
  • Create New...

Important Information

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