Minecraft – How to kill all entities of a specific type, EXCEPT the youngest one

minecraft-commandsminecraft-java-edition

I want to create armor stands whenever I stand on a certain block, but when I stand on it, it summons a lot of armor stands.

I tried /kill @e[type=ArmorStand,c=!1] to kill all except the newest one but it killed all of them.

What should I do to remove all except the youngest?

Best Answer

Make a scoreboard

/scoreboard objectives add age dummy age

put a commandblock by a fill clock and type in

/execute @e[score_age=0,type=ArmorStand] ~ ~ ~ /scoreboard players add @e[type=ArmorStand] age 1

put another commandblock by a fill clock and type in

/kill @e[type=ArmorStand,score_age=2]