Jump to content

Blockstate not updating


h3tR

Recommended Posts

Hi,

I'm making a block that has responsive textures.
for example a "light" that indicates if the machine is powered or not.

It is used by a BlockEntity and the BlockState updates inside a method being called by its ticker (server side).

 

Unfortunately it does not actually update at all.
I'm quite sure the issue is not with the blockstates file itself because I can set it in getStateForPlacement()

 

Here is the code:

 @Override
    public void tickServer() {
        super.tickServer();
        BlockState updatedState = level.getBlockState(worldPosition);

        if(energyStorage.getEnergyStored()<=0) {
           level.setBlock(worldPosition,updatedState.setValue(PepsiMcBlockStateProperties.BOTTLING, PepsiMcBlockStateProperties.BottlerActivity.NONE).setValue(BlockStateProperties.POWERED, false),Block.UPDATE_ALL);
        }else{
            updatedState.setValue(BlockStateProperties.POWERED,true);
            if(Progress>0&&itemHandler.getStackInSlot(0).sameItem(new ItemStack(PepsiMcItem.EMPTY_BOTTLE.get())))
                level.setBlock(worldPosition,updatedState.setValue(PepsiMcBlockStateProperties.BOTTLING, PepsiMcBlockStateProperties.BottlerActivity.BOTTLE).setValue(BlockStateProperties.POWERED, false),Block.UPDATE_ALL);
            else if(Progress>0&&itemHandler.getStackInSlot(0).sameItem(new ItemStack(PepsiMcItem.EMPTY_CAN.get())))
                level.setBlock(worldPosition,updatedState.setValue(PepsiMcBlockStateProperties.BOTTLING, PepsiMcBlockStateProperties.BottlerActivity.CAN).setValue(BlockStateProperties.POWERED, false),Block.UPDATE_ALL);
            else
                level.setBlock(worldPosition,updatedState.setValue(PepsiMcBlockStateProperties.BOTTLING, PepsiMcBlockStateProperties.BottlerActivity.NONE).setValue(BlockStateProperties.POWERED, false),Block.UPDATE_ALL);
        }
        assert level != null;
        level.setBlockAndUpdate(worldPosition,updatedState);

    }

 

Feel free to ask for more code if needed.

Thanks!

Edited by h3tR
footer
Link to comment
Share on other sites

11 minutes ago, ChampionAsh5357 said:

Provide the entire class and any related block classes. You seem to be overriding some custom code called `tickServer` which doesn't help us see whether the code is called. Additionally, most of the fields used are not in the associated classes you mentioned, so it would be hard to pinpoint what you are trying to convey.

I have provided the Block, BlockEntity, custom BlockStateProperty Class and the Method my initial post overrides below (in order)

for context in the final method getRecipe returns an Optional<BottlerRecipe> which just gets the recipe if there is one.

public class AutomatedBottlerBlock extends HorizontalFacedBlock implements EntityBlock {

	public AutomatedBottlerBlock() {
		super(Properties
				.of(Material.PISTON)
				.strength(4.5f,15)
				.sound(SoundType.METAL)
				.requiresCorrectToolForDrops());
	}
	
	
	
	@SuppressWarnings("deprecation")
	public void onRemove(BlockState state, Level level, BlockPos pos, BlockState secondState, boolean p_196243_5_) {
	      if (!state.is(secondState.getBlock())) {
	         BlockEntity blockEntity = level.getBlockEntity(pos);
	         if (blockEntity instanceof AutomatedBottlerEntity automatedbottlerentity) {
				 Containers.dropContents(level, pos, automatedbottlerentity.getNNLInv());
	            level.updateNeighbourForOutputSignal(pos, this);
	         }

	         super.onRemove(state, level, pos, secondState, p_196243_5_);
	      }
	   }

	@Override
	public @NotNull InteractionResult use(BlockState state, Level world, BlockPos pos,
										  Player plr, InteractionHand hand, BlockHitResult hit) {
		if (!world.isClientSide()) {
			BlockEntity entity = world.getBlockEntity(pos);
			if(entity instanceof AutomatedBottlerEntity) {
				NetworkHooks.openGui(((ServerPlayer)plr), (AutomatedBottlerEntity)entity, pos);
			} else {
				throw new IllegalStateException("Container provider is missing!");
			}
		}

		return InteractionResult.sidedSuccess(world.isClientSide());
	}


	@Override
	public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
		return PepsiMcBlockEntity.AUTOMATED_BOTTLER_BLOCK_ENTITY.get().create(pos, state);
	}

	@Nullable
	@Override
	public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState state, BlockEntityType<T> type) {
		if (level.isClientSide()) {
			return null;
		} else {
			return (level1, pos, state1, tile) -> {
				if (tile instanceof AutomatedProcessingBlockEntity Machine) {
					Machine.tickServer();
				}
			};
		}

	}

	@Override
	protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
		super.createBlockStateDefinition(builder);
		builder.add(BlockStateProperties.POWERED);
		builder.add(PepsiMcBlockStateProperties.BOTTLING);
	}

	@Nullable
	@Override
	public BlockState getStateForPlacement(BlockPlaceContext context) {
		return super.getStateForPlacement(context)
				.setValue(BlockStateProperties.POWERED,false)
				.setValue(PepsiMcBlockStateProperties.BOTTLING, PepsiMcBlockStateProperties.BottlerActivity.NONE);
	}
}
public class AutomatedBottlerEntity extends AutomatedProcessingBlockEntity implements MenuProvider {

    public AutomatedBottlerEntity(BlockPos pos, BlockState state) {
        super(PepsiMcBlockEntity.AUTOMATED_BOTTLER_BLOCK_ENTITY.get(), pos, state, 1000, 5);
    }

    protected Optional<BottlerRecipe> getRecipe(){
      return this.getLevel().getRecipeManager().getRecipeFor(BottlerRecipe.BottlerRecipeType.INSTANCE, getSimpleInv(),this.getLevel());
    }

    protected void finishProduct() {
        Optional<BottlerRecipe> recipe = getRecipe();
        recipe.ifPresent(iRecipe->{
            itemHandler.extractItem(0, 1, false);
            itemHandler.extractItem(1, 1, false);
            itemHandler.extractItem(2, 1, false);
            itemHandler.insertItem(3, iRecipe.getResultItem(), false);
            itemHandler.insertItem(4, iRecipe.getByproductItem(), false);
            setChanged();
        });
    }

    @Override
    protected int getOutputSlot() {
        return 3;
    }

    @Override
    protected int getByProductSlot() {
        return 4;
    }

    @Override
    public void tickServer() {
        super.tickServer();
        BlockState updatedState = level.getBlockState(worldPosition);

        if(energyStorage.getEnergyStored()<=0) {
           level.setBlock(worldPosition,updatedState.setValue(PepsiMcBlockStateProperties.BOTTLING, PepsiMcBlockStateProperties.BottlerActivity.NONE).setValue(BlockStateProperties.POWERED, false),Block.UPDATE_ALL);
        }else{
            updatedState.setValue(BlockStateProperties.POWERED,true);
            if(Progress>0&&itemHandler.getStackInSlot(0).sameItem(new ItemStack(PepsiMcItem.EMPTY_BOTTLE.get())))
                level.setBlock(worldPosition,updatedState.setValue(PepsiMcBlockStateProperties.BOTTLING, PepsiMcBlockStateProperties.BottlerActivity.BOTTLE).setValue(BlockStateProperties.POWERED, false),Block.UPDATE_ALL);
            else if(Progress>0&&itemHandler.getStackInSlot(0).sameItem(new ItemStack(PepsiMcItem.EMPTY_CAN.get())))
                level.setBlock(worldPosition,updatedState.setValue(PepsiMcBlockStateProperties.BOTTLING, PepsiMcBlockStateProperties.BottlerActivity.CAN).setValue(BlockStateProperties.POWERED, false),Block.UPDATE_ALL);
            else
                level.setBlock(worldPosition,updatedState.setValue(PepsiMcBlockStateProperties.BOTTLING, PepsiMcBlockStateProperties.BottlerActivity.NONE).setValue(BlockStateProperties.POWERED, false),Block.UPDATE_ALL);
        }
        assert level != null;
        level.setBlockAndUpdate(worldPosition,updatedState);

    }

    @Override
    protected ItemStackHandler createHandler() {

        return new ItemStackHandler(5) {

            @Override
            protected void onContentsChanged(int slot) {
                setChanged();
            }

            @Override
            public int getSlotLimit(int slot){
                if(slot == 4)
                    return 16;
                return 64;
            }


            @Override
            public boolean isItemValid(int slot, @Nonnull ItemStack stack) {
                return switch (slot) {
                    case 0 ->
                            stack.getItem().getDefaultInstance().getTags().toList().contains(PepsiMcTags.Items.BOTTLING_CONTAINER);
                    case 1 ->
                            stack.getItem().getDefaultInstance().getTags().toList().contains(PepsiMcTags.Items.BOTTLING_LABEL);
                    case 2 ->
                            stack.getItem().getDefaultInstance().getTags().toList().contains(PepsiMcTags.Items.BOTTLING_LIQUID);
                    case 3 ->
                            stack.getItem().getDefaultInstance().getTags().toList().contains(PepsiMcTags.Items.BOTTLED_LIQUID);
                    case 4 -> stack.getItem() == Items.BUCKET;
                    default -> false;
                };
            }
            @Override
            @Nonnull
            public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) {
                if(!isItemValid(slot, stack)) {
                    return stack;
                }
                return super.insertItem(slot, stack, simulate);
            }
        };
}

    @Override
    protected LazyOptional<IItemHandler> getOutHandler() {
        return LazyOptional.of(()->new IItemHandler(){

            @Override
            public int getSlots() {
                return 2;
            }

            @NotNull
            @Override
            public ItemStack getStackInSlot(int slot) {
                return itemHandler.getStackInSlot(slot+3);
            }

            @NotNull
            @Override
            public ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate) {
                return itemHandler.insertItem(slot+3, stack, simulate);
            }

            @NotNull
            @Override
            public ItemStack extractItem(int slot, int amount, boolean simulate) {
                return itemHandler.extractItem(slot+3,amount,simulate);
            }

            @Override
            public int getSlotLimit(int slot) {
                return itemHandler.getSlotLimit(slot+3);
            }

            @Override
            public boolean isItemValid(int slot, @NotNull ItemStack stack) {
                return itemHandler.isItemValid(slot+3,stack);
            }
        });
    }

    @Override
    public @NotNull Component getDisplayName() {
        return new TranslatableComponent("block.pepsimc.automated_bottler");
    }

    @Nullable
    @Override
    public AbstractContainerMenu createMenu(int id, @NotNull Inventory inv, @NotNull Player p_39956_) {
        return new AutomatedBottlerMenu(id,inv,this,dataAccess);
    }
}
public class PepsiMcBlockStateProperties {
    public static final EnumProperty<BottlerActivity> BOTTLING = EnumProperty.create("bottling", BottlerActivity.class);


    public enum BottlerActivity implements StringRepresentable {
        NONE("none"),
        CAN("can"),
        BOTTLE("bottle");

        private final String name;

        private BottlerActivity(String p_61824_) {
            this.name = p_61824_;
        }

        public String toString() {
            return this.getSerializedName();
        }

        public @NotNull String getSerializedName() {
            return this.name;
        }
    }
}
   public void tickServer() {
        if (getRecipe().isPresent() && (PreviousRecipe==null || PreviousRecipe.isEmpty() || getRecipe().get() != PreviousRecipe.get())) {
            Goal = getRecipe().get().ticks;
        }
        PreviousRecipe = getRecipe();
        if(energyStorage.getEnergyStored()>0 && getRecipe().isPresent() &&
                (isSlotEmpty(getOutputSlot()) || (isSlotFull(getOutputSlot())) && getRecipe().get().getResultItem().sameItem(itemHandler.getStackInSlot(getOutputSlot())) &&  (getByProductSlot() < 0 ||isSlotEmpty(getByProductSlot()) || (isSlotFull(getByProductSlot())) && getRecipe().get().getByproductItem().sameItem(itemHandler.getStackInSlot(getByProductSlot()))))) {
            Progress++;
            if(Progress>=Goal){
                Progress = 0;
               finishProduct();
            }
            energyStorage.consumeEnergy(1);
        }else{
            Progress = 0;
        }
    }
Link to comment
Share on other sites

You never actually update the state to powered.

This code does not mutate the updatedState, it creates a new BlockState which you discard. The name setValue() is misleading.

updatedState.setValue(BlockStateProperties.POWERED,true);

 

So this later code at the end just sets the BlockState back to what it was when you called getBlockState(worldPosition), i.e. the original value.

level.setBlockAndUpdate(worldPosition,updatedState);

All your other supposed changes to the updatedState will also be discarded/overwritten.

 

I don't understand why you are continually calling setBlockState(). Shouldn't you just be calculating the new BlockState then calling setBlockState() once at the end?

 

BTW. You don't need to call that level.getBlockState(worldPosition);

Your BlockEntity already knows its own BlockState. You can get it using this.getBlockState()

Edited by warjort
  • Thanks 1

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

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.



×
×
  • Create New...

Important Information

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