6
$\begingroup$

I am trying to add a series to text in blender using python Presently I am using these lines of code

bpy.ops.object.text_add()
ob=bpy.context.object
ob.data.body = "my text"

Is there a way that I can add my text while adding the text object itself?

$\endgroup$
2
  • 1
    $\begingroup$ This question needs a bit more clarity – are you simply trying to reduce the number of lines of code, improve the efficiency of the code, or something else? $\endgroup$ – Christopher Gearhart Jan 12 '20 at 0:54
  • $\begingroup$ reduce the lines of code! $\endgroup$ – Raghunandan Venkatesh Jan 12 '20 at 13:16
8
$\begingroup$

The preferred way to perform the above operation would be to create the data blocks and link them to the scene using the "low-level" API - RNA methods and attributes - instead of operators to achieve better runtimes and avoid incorrect context issues.

The following code replaces the operator call above to achieve the same behavior:

font_curve = bpy.data.curves.new(type="FONT", name="Font Curve")
font_curve.body = "my text"
font_obj = bpy.data.objects.new(name="Font Object", object_data=font_curve)
bpy.context.scene.collection.objects.link(font_obj)

If you're simply looking to reduce the lines of code by combining the creation of the text and specifying the body, the following code works similarly:

bpy.data.curves.new(type="FONT", name="Font Curve").body = "my text"
font_obj = bpy.data.objects.new(name="Font Object", object_data=bpy.data.curves["Font Curve"])
bpy.context.scene.collection.objects.link(font_obj)
$\endgroup$
2
  • 1
    $\begingroup$ making above a method eg def add_text(body_text, collection=bpy.context.collection): will also ultimately reduce the lines of code if adding a lot of text objects. $\endgroup$ – batFINGER Jan 13 '20 at 18:36
  • 2
    $\begingroup$ Note there is a problem with the suggested second method : When running the code more than once, all text objects will share the same Font data (the first one), and all subsequent ones will get queued up for the garbage collector because they aren't linked to any user object. $\endgroup$ – Gorgious May 27 at 8:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.