[BlockPlaceEvent] How to get the block that was in the location before the block was placed?

Discussion in 'Plugin Development' started by OHQCraft, Mar 18, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    OHQCraft

    So the title might not make sense, but I want to get the block that was at the Location of the block placed before the block was placed. Normally this is "Material.AIR", but if it is not I want to "event.setCancelled(true);". Because I don't want blocks to override previous blocks... Such as a normal block overriding Wheat, Fire or Grass. I am looking for a way to get the previous block or cancel out overlapping.

    Thanks.:)
     
  2. Offline

    Amgis

    OHQCraft
    Code:
    BlockPlaceEvent event;
     
    BlockState block = event.getBlockReplacedState();
    Note that you cannot retrieve the original Block from the BlockPlaceEvent, as a Block is bound to the world. Once it is replaced, it no longer exists.
     
  3. Offline

    OHQCraft

    I still don't get it... Is it possible?
     
  4. Offline

    Amgis

    OHQCraft
    It's not a problem. A BlockState object is the same as a Block object, only that method calls to a BlockState object will not affect the world in any way.
    Code:java
    1. @EventHandler
    2. public void onBlockPlace(BlockPlaceEvent event) {
    3.  
    4. Block newBlock;
    5. BlockState oldBlock;
    6.  
    7. newBlock = event.getBlock();
    8. oldBlock = event.getBlockReplacedState();
    9.  
    10. if(newBlock != null && oldBlock != null) {
    11.  
    12. if(oldBlock.getType() != Material.AIR) {
    13.  
    14. event.setCancelled(true);
    15. }
    16. }
    17. }
     
    OHQCraft likes this.
  5. Offline

    OHQCraft

    Thanks, it worked!
     
Thread Status:
Not open for further replies.

Share This Page