-1

Is it possible to put a runnable in an if statement, because I need it, if the player has a chiseled sandstone underneath it, then it should take the block out after 5 seconds, is it possible to do it this way or do I need another way? Intellij IDEA, java plugin minecraft. Code:

 if (player.getLocation().getBlock().getRelative(BlockFace.DOWN).getTypeId() == 179) {
            new BukkitRunnable() {
                @Override
                public void run() {
                    loc.getBlock().setType(Material.AIR);
                }
            }.runTaskLater(plugin, 100);
        }
console
  • 11
  • 4

2 Answers2

1

I tried this in regards to plain core java and it works fine

 int x = 10;
    Timer timer = new Timer("Timer");
    if (x > 0) {
        TimerTask task = new TimerTask() {
            public void run() {
                System.out.println("Task performed on: " + new Date() + "n" + "Thread's name: "
                        + Thread.currentThread().getName());
                timer.cancel();
            }
        };

        long delay = 1000L;
        timer.schedule(task, delay);
    }
output Task performed on: Sat Jul 03 13:49:54 IST 2021nThread's name: Timer
        

so I assume what you mentioned should also work

anish sharma
  • 568
  • 3
  • 5
1

I tested the code and it is working fine. I assigned the BukkitRunnable to a variable to have a chance to cancel the task in some special cases, but if you wish you could remove it.

I think the problem was in the Runnable body where you forgot to go one block under the player's current location and you tried to set the air to air. Also i would suggest to use getType() instead of getTypeId().

Hope it will work fine like in my case. :)

Block blockUnder = player.getLocation().getBlock().getRelative(BlockFace.DOWN);

                        if (blockUnder.getType() == Material.CHISELED_SANDSTONE) {
                            BukkitTask task = new BukkitRunnable() {
                                @Override
                                public void run() {
                                    blockUnder.setType(Material.AIR);
                                }
                            }.runTaskLater(plugin, 20L * 5L);
                        }
L.Levente
  • 21
  • 4