Changing objects visibility in the viewport and while rendering

The easiest way to hide and show rendering objects is to assign animation keys to them. To do this, move the cursor over the eye icon (visibility in the viewport) or camera (visibility when rendering) in the Outliner window, press the “i” key and then manage the created condition in the Graph Editor like the ordinary animation keys.

But this method is not always available. For example, we cannot assign visibility animation keys for collections, Blender will generate errors like:

“hide_viewport” property cannot be animated

or

“hide_render” property can not be animated

However, using the Blender Python API, we can control the visibility of such objects.

Let’s create a simple scene with three objects in their own collection. In practice, there can be lots of meshes in one collection, which allows managing the visibility of all them through the single collection.

Let’s open the Text Editor, internal or external as you like, and create a script that will manage the visibility of the three created collections – “cube”, “monkey” and “sphere”.

At first, define three lists to specify the frames on which we need to change the collection visibility.

We added a new attribute “toggle_visibility_frame” to each collection and assigned it with a list of frame numbers. Through this list, we can conveniently assign frames to change the visibility of the desired collection.

Define the list with the collections to which we assigned the visibility change attribute.

Next, define the function that will compare the current timeline frame number with the list of numbers from the “toggle_visibility_frame” attributes and if the number of the current frame matches the number specified in the list, change the visibility of the collection by hiding or showing it.

Now we need to call this function every time a frame is changed in the timeline. Let’s bind the call of our function to the frame change event through the “frame_change_pre” handler, which calls every time before changing the next frame in the scene.

That’s all.

Full text of our script:

Execute the script by clicking the “Run Script” button and start the animation.

As a result, the collections are shown and hidden in accordance with the assigned frames.