A script to automatically set the focus distance to a referenced focus object without a permanent link

Hello!

There was a user requesting this feature in this old archived thread (which I was unable to reply to):

I shared the same desire for a quick distance value without a permanent link. Here is the description of the need:

Often when we are animating a camera, we want to focus on a certain object quickly. The “Focus on Object” field is very useful for that, since you can take an eye-dropper and select the focus object quickly from the scene. The only problem is that the link is permanent in a way: if it is severed, we lose the focus to that object. I wanted to at least see the correct distance value, based on the focus object, so that I could set the manual “Focus Distance” field to that value after severing the link. But I ended up writing a script that will also set the “Focus Distance” field automatically to the correct value. This script will basically check if the focus object property changes from empty to populated and in that case it will run the distance calculation, print the result in the console and also set the focus distance to that value. So now you can severe the link to the focus object while retaining the focus.

Here is an explanation on how to use the script and the script itself: