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.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Whenever I attempt to join my friend's MC server (hosted through Bisect Hosting) my game crashes, when it crashes I get an error report that says it may be because I was not allocating enough RAM, despite having allocated (at different times) 4G, 6G, 8G, 9G, 10G, 14G, 16G, and 20G all of which my game still crashed. My laptop has 32 GB of RAM so I am hesitant to go above 20, and I feel as though it shouldn't need it.  To elaborate more on the crashes, I am able to join the world, but when the "select origin" screen pops up whenever I click the screen anywhere the game goes white, my curser pinwheels and I get the "Minecraft has stopped responding" message. I did eventually try beating it with sheer determination and godlike patience by hitting "wait for the program to respond" and sat at my laptop for 30 minutes at a time until my screen unfroze and it would progress to the next option, but once I got to "select class" it froze for close to an hour so I gave up. Also to clarify, I do not have ANY issues on single-player worlds, in fact, it runs incredibly smoothly, on high settings and a render distance of about 15 chunks I was still getting 30-40 fps (which I am fine with), and on said worlds, I never have any issues or any lag on selecting origin, blessing nor class. This issue only occurs on THIS specific mod pack (to reiterate Cisco's Fantasy Mideaval RPG V4f), and ONLY on multiplayer. I know this for certain because I have another server with some other friends running Enigmatica 9 (the easy version) and I have had no issues. What I have tried to far to remedy the issue: By digging through old Reddit posts, quora responses, and Minecraft forum inquiries, I found the following "solutions" that I attempted and all failed: Uninstalling the mod pack and reinstalling it, updating graphics drivers, updating windows, updating my laptop's stuff (not really sure what to call it, I have a ThinkPad so its though the Lenovo application), I did a Window's defender scan, I tried adding -d64 in JVM arguments, I tried rebooting my laptop numerous times, I've done all of the previous before and after switching it off of power conservation mode (before that I had already put javaw on high-performance settings). The only things I could think of that I have not tried solely because they would be a pain in my rear would be reinstalling java (but whenever that is suggested in forums it seems its for versions before 1.15?) and connecting my laptop to ethernet (since my laptop doesn't have an ethernet port this would be a pain). I also don't think ethernet would solve it as even on WiFi my ping is 31, download is approximately 200 Mbps, and upload is 23 Mbps. If you have any suggestions I am all ears, at this point I feel like I've exhausted all options I can think of and was going to resign myself to just not being able to play on the server but my friend convinced me to make this post just in case someone had an idea.
    • I am new to this and am trying to increase the RAM allocated on my server.  Right now it is only using 2 GB, but I saw people put "java -Xmx4096M -Xms4096M -jar server.jar nogui" in the run.bat file, and I'm not sure where to add it as my run.bat has the following in it.    
    • it works, but before the world opens, it opens a screen listing the now-missing items from the missing mod, and asks me if I'm sure I want to continue. Is there any way for the world to work with the mods, as removing them would lose blocks/items in the world, from the affected mods? (Maybe certain versions/instances/etc of the mods/launcher/etc are compatible??)
    • added a few more and it re-broke lol. Any help with this crash report? last time promise haha https://gist.github.com/it-is-allie/e7297a2485d05ce58c6303b3751a36f2 
    • So I actually managed to fix this issue. I have absolutely no idea why it suddenly started showing changes for me other than changing the createParticle method to create an instance of the particle before returning it. 
  • Topics

×
×
  • Create New...

Important Information

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