10
$\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$ Commented Jan 12, 2020 at 0:54
  • $\begingroup$ reduce the lines of code! $\endgroup$ Commented Jan 12, 2020 at 13:16

1 Answer 1

18
$\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
    Commented Jan 13, 2020 at 18:36
  • 3
    $\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
    Commented May 27, 2021 at 8:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .