Is it possible to use Python to incorporate a lighting element in Blender?

The code used in Blender resulted in an error, as shown in the reference picture. After searching through other posts, I found a working code for Blender 2.80. However, the old API was broken, causing most steps to change.

Question:

As a beginner in Blender, I am seeking helpful tutorials on utilizing Python to manage the software. My objective is to manipulate light sources by using Python methods, such as adding, removing, and editing them. Is it feasible to perform these actions? I appreciate any suggestions provided.



Solution 1:


With the release of Blender 2.80, significant changes were made to the API resulting in the old API becoming obsolete. As a result, the steps for coding have been updated and are provided below.

import bpy
# create light datablock, set attributes
light_data = bpy.data.lights.new(name="light_2.80", type='POINT')
light_data.energy = 30
# create new object with our light datablock
light_object = bpy.data.objects.new(name="light_2.80", object_data=light_data)
# link light object
bpy.context.collection.objects.link(light_object)
# make it active 
bpy.context.view_layer.objects.active = light_object
#change location
light_object.location = (5, 5, 5)
# update scene, if needed
dg = bpy.context.evaluated_depsgraph_get() 
dg.update()


Solution 2:

Answer is Yes!

Look at the recent Python API.

Below is an instance that generates a new Lamp object and situates it in the current scene’s default location of (5, 5, 5).

Blender version 2.63

The script should look like this:

import bpy
scene = bpy.context.scene
# Create new lamp datablock
lamp_data = bpy.data.lamps.new(name="New Lamp", type='POINT')
# Create new object with our lamp datablock
lamp_object = bpy.data.objects.new(name="New Lamp", object_data=lamp_data)
# Link lamp object to the scene so it'll appear in this scene
scene.objects.link(lamp_object)
# Place lamp to a specified location
lamp_object.location = (5.0, 5.0, 5.0)
# And finally select it make active
lamp_object.select = True
scene.objects.active = lamp_object


Frequently Asked Questions