Blender python script to toggle the render and viewport visibility of selected objects

i currently have this code but it only works with one selected object
any help?

import bpy

obj = bpy.context.active_object

if obj:
obj.hide_render = not obj.hide_render
obj.hide_viewport = not obj.hide_viewport

objs= [o for o in bpy.context.selected_objects]

for o in objs:
   o.hide_render = not obj.hide_render
   o.hide_viewport = not obj.hide_viewport

1 Like

didn’t work, i got this error message
Python: Traceback (most recent call last):
File “\Text”, line 6, in
NameError: name ‘obj’ is not defined. Did you mean: ‘objs’?

typo

objs= [o for o in bpy.context.selected_objects]

for o in objs:
   o.hide_render = not o.hide_render
   o.hide_viewport = not o.hide_viewport

well, now it turns off render and viewport visibility but doesn’t turn it back on
any idea how to get it to work?

because you hid them, they’re not selected anymore. an outliner selection is not the same as a viewport selection.

1 Like

so how do i make it work?