Is there anyway to input a command upon the first player joining and the last player leaving my Minecraft server?
-
We're running a modded server with Serene Seasons and I'd like to toggle the season cycle gamerule whenever players are online then again when everyone is offline. I don't seem to have any automated tasks features on my server dashboard so I'm wondering how I might do so with Commandblocks or if there are any alternative options.
-
Simple
If you don't care about it running on every tick, this is the simpliest solution:
/execute if entity @a[limit=1] run gamerule DoSeasonsCycle true /execute unless entity @a[limit=1] run gamerule DoSeasonsCycle false
The only reason I'm giving a more complex afterwards is that I'm not sure if this would flood the server logs
A bit extra
But if you want to run it a single time, and not use datapacks:
Summary answer:
Run in your chat once:
/scoreboard objectives add AnyPlayer dummy /scoreboard players set $State AnyPlayer 0
In loop:
/execute if score $State AnyPlayer matches 0 if entity @a[limit=1] run gamerule DoSeasonsCycle true /execute if score $State AnyPlayer matches 0 if entity @a[limit=1] run scoreboard players set $State AnyPlayer 1
/execute if score $State AnyPlayer matches 1 unless entity @a[limit=1] run gamerule DoSeasonsCycle false
/execute if score $State AnyPlayer matches 1 unless entity @a[limit=1] run scoreboard players set $State AnyPlayer 0
Explanation
We need a scoreboard to track the states:
- 0: No players
- If 0 and there is a player: Someone just joined
- 1: At least one player
- If 1 and there is no player: Last person left
Create the scoreboard and set its inital state to 0:
/scoreboard objectives add AnyPlayer dummy /scoreboard players set $State AnyPlayer 0
The idea is, if you don't have players and the score is set to 1 (which means there were), run the commands followed by setting the score to 0. The opposite idea applies.
If players left:
/execute if score $State AnyPlayer matches 1 unless entity @a[limit=1] run (your gamerule command here, set to false) /execute if score $State AnyPlayer matches 1 unless entity @a[limit=1] run scoreboard players set $State AnyPlayer 0
Once a player joins:
/execute if score $State AnyPlayer matches 0 if entity @a[limit=1] run (your gamerule command here, set to true) /execute if score $State AnyPlayer matches 0 if entity @a[limit=1] run scoreboard players set $State AnyPlayer 1