Link object location to a text content

Hi everybody!
Can someone help me to link the content of a text object to the location of another object?

I’m very new in coding and so far I have done this

import bpy
bpy.data.objects[‘Text’].data.body = “%i m” %bpy.context.object.location[1]

Which is good enough but:
1.- I’m not getting the whole value jus the “integer” part not the decimal part
2.- How can I do it like a live value (always linking and showing the value)
3.- How can I manipulate the value shown. Example change the decimal point position and precision


Thanks very much

In python you can cast a value into a string by using str(value) or value.__str__().

So your code becomes

import bpy

bpy.data.objects['Text'].data.body = str(bpy.context.active_object.location[1])

Result :
image

However as you noticed this writes all the significant digits of the float values, which we don’t realistically want.

Python has a handy round(value, digits) method to do this for us.

import bpy

location = bpy.context.active_object.location[1]
location = round(location, 3)  # Round the location 3 digits after the dot
bpy.data.objects['Text'].data.body = str(location)

Result :

image

If you wanted this value to update automatically, you would need to add a driver between those two properties. Unfortunately the body of a text object can’t be animated. There is one solution though, using python handlers to actively update the value each time the dependency graph gets updated, for instance. There are a few handlers which you can find there https://docs.blender.org/api/current/bpy.app.handlers.html

The depsgaph_update_post handler will fire everytime you change anything in your scene. That may be a bit overkill but since drivers won’t work, that seems like a good fit. If you are doing animation, you may rather want to use frame_change_post which will fire everytime the frame is changed in the animation timeline.

import bpy

def update_body(scene, depsgraph):
    obj = bpy.context.active_object
    text = bpy.data.objects.get('Text')
    if not obj or not text:
        return
    location = obj.location[1]
    location = round(location, 3)  # Round the location 3 digits after the dot
    text.data.body = str(location)

bpy.app.handlers.depsgraph_update_post.append(update_body)

Result :

BSE.111

1 Like

Awesome! That was quick.
Thanks a lot!

1 Like