Help with Text Datablock syntax/methodology

I’m using the following to add a Python to a game object. What I need is the correct syntax/methodology to reference a text datablock. The first part of the 2nd line (item_object.game.controllers[“control_item”].text) is correct, but needs a Text Datablock rather than a string. I’ve written the script I want to execute (“my script”) which is stored in Blender (and I assume it’s stored as a datablock), but I don’t know how to reference it by name and therfore assign it to the controller.

bpy.ops.logic.controller_add(type='PYTHON', name="control_item", object=item_object.name)
item_object.game.controllers["control_item"].text = "my script"

Any suggestions?

A2G

If I remember good, the python script has to live in a TEXT (open Scripting and add a new text window give it at once a descriptive name myscriptfor.py or so :wink: !) part and the name of that is needed as a reference the text after the =

bpy.data.texts.new(“hello”)
bpy.data.texts[“hello”].write(“world”)

The Python script I’m attempting to link to already resides internal to Blender. I believe I can access it using the following …

txt_block = os.path.join(os.path.basename(bpy.data.filepath), "Text\my script")

… but when I attemp to assign txt_block to the controller.text, the console says …


TypeError: bpy_struct: item.attr= val: PythonController.text expected a Text type, not set

@dustractor - I understand that what you provided will create a new datablock, but how do I reference a datablock that already exists and is available via the Text editor?

Just in case anyone is interested … it took me some time and a little trial & error testing … but I finally figured it out … My original question was basically how to link a premade script to a logic controller programmatically through Python … the following works … I’m happy now :stuck_out_tongue:

bpy.ops.logic.controller_add(type='PYTHON', name="control_item", object=item_object.name)
item_object.game.controllers["control_item"].text = bpy.data.texts["my script"]