Minecraft – Add players to team if they are within range

minecraft-commandsminecraft-java-edition

I'm trying to create a command block which adds players to the team "spawn" if they are within 2 blocks.

I can get it to add players to spawn, but not remove or change team when they go outside of the range?

Once they leave the spawn distance they are supposed to leave the team but this isn't working.

Can someone please explain why it isn't working, and offer a solution?

My commands are as follows:

execute if entity @a[distance=..2] run team join Spawn @s[distance=..2]
execute if entity @a[distance=2..] run team leave @s[distance=2..]

I even tried making another team for the players to join instead but this also doesn't work.

execute if entity @a[distance=3..] run team join notSpawn @s[distance=3..]

Best Answer

The @s selector refers to the entity which is executing that command. Since the command is being executed by a command block, @s is referring to the command block and that's why it's not working.

There is a much easier way of doing this which doesn't require you to test for anything.

To add someone within range to a team: /team join someTeam @a[distance=..5]

And to remove players from the team if they are out of range: /team leave @a[team=someTeam,distance=5..]