How can I allow one player to receive an item or XP without another player being affected?

How can I allow one player to receive an item or XP without another player being affected if he/she is too close. I used command blocks with buttons for players to buy items and when another player is too close they lose their xp points.


Since you mention issues with other players being too close, you probably know about target selectors and have been using @p or @a[r=...] to select the nearest player or all within a really small range. The problem looks to be arising from either multiple players being within the range, or @p targeting different players in different command blocks.

So how do we fix that? One approach would be to use a scoreboard objective to keep track of a single person purchasing. First, set up a state objective by entering

/scoreboard objectives add purchasing dummy

This adds an objective called "purchasing" which we will use to ensure only one player is affected. The idea is that you set it up so that pressing the button to buy an item gives exactly one of the players a score of 1 in this objective, do all your other commands (such as verifying sufficient currency, xp, etc.) with @a[score_purchasing=1] and then reset it back to zero when you've done all of that. For example, this setup:

enter image description here

With commands of

1) /scoreboard players add @p purchasing 1
2) /testfor @a[score_purchasing=1,lm=15]
3) /give @a[score_purchasing=1] diamond
4) /xp -15L @a[score_purchasing=1]
5) /scoreboard players reset @a purchasing

Will (in approximately* this order) designate the closest player as the one who is purchasing an item, check if they have at least 15 levels, and subtract 15 levels and give them a diamond if so. After that, the purchasing score of everyone is set back to zero. Note that the torch and repeater is needed in this case to (respectively) reset the /testfor command and ensure the scoreboard objective reset occurs last.


*Strictly speaking, the order of execution of the pairs of 1,2 and 3,4 is non-deterministic, but they will still execute within the same tick (1/20 sec). This often isn't an issue, but can be changed by using fill clocks (\fill commands with redstone blocks) if needed.