This is an old revision of the document!
Giving a block state
Every type of block in Minecraft is represented by a singular Block
instance.
This makes it impossible to change a specific block's state by simply changing the Block
instance's state,
as every other block of that type will be affected!
But, what if I do want to give a singular block state, so it can change based on some condition?
This is what BlockState
s are for.
Say we wanted a block to have a hardness of 0.5
normally, but if we right click it before we try to break it,
it would become harder and gain a hardness of 2
.
First we define the boolean property of the block - whether or not it is hard:
public class MyBlock extends Block { public static final BooleanProperty MyBlockIsHard = BooleanProperty.of("is_hard"); }
Then we need to register the property by overriding appendProperties
:
public class MyBlock extends Block { ... @Override protected void appendProperties(StateFactory.Builder<Block, BlockState> stateFactory) { stateFactory.add(MyBlockIsHard); } }
Then we need to set the default state of our property in the block constructor:
public class MyBlock extends Block { ... public MyBlock(Settings settings) { super(settings); setDefaultState(getStateFactory().getDefaultState().with(MyBlockIsHard, false)); } }
Now, to set the property we need to call world.setBlockState
:
public class MyBlock extends Block { ... @Override public boolean activate(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult blockHitResult) { return super.activate(state, world, pos, player, hand, blockHitResult); } }
And to use the property we call blockState.get(<our-property-name>)
:
public class MyBlock extends Block { ... @Override public float getHardness(BlockState blockState, BlockView blockView, BlockPos pos) { boolean isHard = blockState.get(MyBlockIsHard); if(isHard) return 2.0f; else return 0.5f; } }