Under the system actions:
Sort Z order
Sort the Z order of instances of a given object according to an instance variable. This effectively removes all instances from their Z order, sorts them, then inserts the sorted sequence back in to the holes left behind. This means if the instances are spread across a range of layers, they will be sorted in the same Z order locations, maintaining the same order relative to other instances on those layers. Note this action is much faster than using an ordered For each with an action like Send to front/back, so this action should be the preferred way to sort the Z order of large numbers of instances.
So, when the object changes y, or every tick, instance set variable myz to instance.y
Sorting would be sort z order by myz