How to spawn an entity and then despawn it after a given time?

Discussion in 'Spigot Plugin Help' started by ST_DiamondSword, Jul 16, 2021.

  1. On a particular event, I need to spawn a wolf and then despawn it after 30 seconds. This is what I tried:

    Code (Java):
    if (condition) {
        Entity entity = World.spawnEntity(Location, EntityType.WOLF);
        try {
            TimeUnit.SECONDS.sleep(30);
            entity.remove();
        } catch (InterruptedException e) {
            e.printStackTrace();
           
        }
    }
    The wolf is getting spawned, but it's not de-spawning. I'm not getting any errors in Stack Trace either. What do I do?
     
  2. Hello,

    Never pause/sleep the main thread, it will block everything on the main thread.
    You can use the BukkitScheduler#runTaskLater to run a task X ticks later.
     
    • Like Like x 1
  3. Code (Java):
        Entity entity = World.spawnEntity(Location, EntityType.WOLF);
                        new BukkitRunnable() {
                            @Override
                            public void run() {
                                entity.remove();
                            }
                        }.runTaskLater(Main.getMain(), 20);
    Hope this is helpful :D
     
    • Like Like x 1
  4. Oh don't froget to set 20 to 600

    600 = 30 seconds
     
    • Agree Agree x 1
  5. i would just multiply the ticks 20*30 = 30 seconds (cause 20ticks = 1sec)
     
    • Agree Agree x 1
  6. What is the getMain() method? I don't see an option for that. When I use Main.getPlugin(), it gives me an error saying: "getPlugin cannot be applied to '()'"
     
  7. You just need an instance of your Main class what i like to do is in your class you have
    Code (Text):
    private Main plugin;
    public Class(Main plugin){
      this.plugin = plugin
    }
    this way in the area where you have Main.getMain() you just put plugin.
     
    • Agree Agree x 1