How do I make a diamond sword that, when it hits a mob, executes a command?

I have already made a scoreboard objective for "used:minecraft.diamond_sword", but I don't know what to do next.


This scoreboard will register whenever you use a diamond sword, which means it will register whenever you hit a mob or break a block. Lets call this scoreboard sword.

If you want to execute as everyone who has the score higher then 0, you can do:

/execute as @a[scores={sword=1..}] at @s run command

The '1..' Means anything or anyone that has the score of 1 or higher. You can also do X..Y, and it will select every player within the range of X to Y (Including themselves).

However you might run into a problem: The scoreboard will not reset. You can simply add the following command into a repeat command block.

/scoreboard players set @a sword 0