Python Script Manager to Set MoText Keyframes at Time


#1

I have a MoText object in my scene and I want to set many keyframes that change its text value every 8 frames to a random number. I want to use keyframes (NOT Xpresso) so I can offset the time randomly in a cloner. I’m trying to use Python in the Script Manager to set the keyframes, but I’m struggling to figure it out. Running the following code does not set the keyframes, and I don’t understand why:

import c4d
from c4d import gui
import math
import random

# c4d helper function
def set_value_at_frame(frame, value, curve):
  keyTime = c4d.BaseTime(frame,  doc.GetFps())
  added = curve.AddKey(keyTime)
  if added is None:
    raise TypeError("cannont create a key")
  firstKey = added["key"]
  kIndex = added["nidx"]
  firstKey.SetValue(curve, value)
  curve.SetKeyDefault(doc,kIndex)

def main():
  random.seed(0)
  
  MoText = doc.SearchObject("MoText")
  CHANGE_EVERY_N_FRAMES = 8
  trY = c4d.CTrack(MoText, c4d.DescID(c4d.PRIM_TEXT_TEXT))
  curve = trY.GetCurve()
  for ii in range(0, 1680, CHANGE_EVERY_N_FRAMES):
    val = random.choice(list(range(0, 10)))
    print val
    set_value_at_frame(ii, str(val), curve)
  MoText.InsertTrackSorted(trY)

Running this code in the script manager says that a float is required, but I don’t understand why; shouldn’t the text parameter take a string? I don’t think I’m dealing with the keyframe track properly, but I don’t understand how to in this situation. What is wrong with my code? Can you post a simple example that sets keyframes for the text of a MoText object?


#2

You need to use SetGeData(), as SetValue() only takes float parameters as documented.

Additionally I’d specify the data type of the DescId properly. Just to avoid confusion. Like so: c4d.DescID(c4d.DescLevel(c4d.PRIM_TEXT_TEXT, c4d.DTYPE_STRING))

And in the end of your script you should call c4d.EventAdd() to make C4D aware of changes and update the UI.

Cheers


#3

Thank you very much, that worked perfectly. I didn’t realize that there were two functions that needed to be used to set keyframe values.


#4

Welcome

In such cases the C++ API documentation can be helpful. These contain the “Manual” sections , which provide a bit more overview and context. For example here: the Animation and the CKey manuals. And no worries, most information should be easily transferred to Python. I think, those manuals are also coming to the Python doc, as the SDK team at Maxon finds time and sees fit.