Autofocus on Layers
Automate the focus distance of your camera to keep a particular layer in focus - also transitions between layers are possible.
Just apply this expression to the "Focus Distance" property of your camera layer. Now the meaning of the "Focus Distance" value changed: 1 does not mean "focus distance 1px" anymore, but means "keep layer 1 in focus" instead.
Transitions
To do a focus transition from layer 3 to layer 5 of your comp, simply add two keyframes - first with value 3 and second with value 5. If you add easing to your keyframes, the focus pull will ease accordingly, too! Of course, you can add as many keyframes as you want.
Explicitly linking layers
The only inconvenience of using layer indices for the focus distance is that you have the update the keyframes accordingly, if the index of your focus layers changes (if you add or delete other layers). To avoid this, you can connect layers explicitly by setting "Choose Layer by" to "explicit link". Now properties "Focus Layer 1" to "Focus Layer 30" appear, where you can connect layers that you want to focus on.
Example: Say you have in total five layer that you want to focus on. Then simply connect the first five "Focus Layer" properties of the iExpression to these five layers. Now keyframing the focus distance to 1 does not mean to focus on layer #1 of the comp anymore, but instead it means to focus the layer that you connected at the "Focus Layer 1" property of the iExpression - and this will not change, no matter how the actual index of the connected layer might change.
Note - Missing Transition Parameters: Older versions of this expressions had some transition parameters to control the timing from one layer to the next one. In the new version, the easing is directly taken from the easing of the keyframes. Therefore, the easing parameters are not needed anymore.
Download at aescripts.com