Home Coding, Scripting, Shaders

maya python - read from text file, iterate through lines per keyframe and display to screen

grand marshal polycounter
Offline / Send Message
Alex_J grand marshal polycounter
Here's a script that will read through a text file, use line breaks as a delimiter, and show each line associated with timeline frame, starting from 0.

Useful for synching animations with dialog or notes, which is really hard to do if your text is in a separate app. It's crazy that maya doesn't seem to have any native way to do this as far as I can tell. 
blue pencil has key frameable text but you have to type per frame and it's unstable at time of writing.

 Easy way to make a shelf button: Paste this into the script editor, then select all, middle mouse drag to your shelf.
To refresh the text if you made some changes, just click the shelf button again

Note, I don't know Python. ChatGPT generated the code. If you want to use it to help make simple tools like this, it is most helpful if you only give it one small part of the job at a time, get that working, and then combine it all together. For example with this, first just get a message to display, then get a message to display at frame changes, then read lines from text, etc. If you do it like that you can get things to work, but if you try to have it make entire script like this at once, won't work.

Python code: 

import maya.cmds as cmds

# Global variable to store the lines from the file
lines = []

# Function to display an in-view message based on the current frame
def display_message_at_current_time():
    # Get the current time (frame)
    current_frame = int(cmds.currentTime(query=True))
    # Check if the current frame has a corresponding string
    if current_frame < len(lines):
        # Get the message for the current frame
        message = lines[current_frame]
        # Display the in-view message
        cmds.headsUpMessage(message, time = 2, verticalOffset = 200)

# Function to read strings from a file and set up the scriptJob
def read_strings_from_file(file_path):
    global lines
    lines = []

    # Read the file and store each line in the lines array
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = [line.strip() for line in file.readlines()]
    except IOError:
        cmds.error("Could not open file " + file_path)
        return

    # Create a scriptJob that triggers when the time changes
    cmds.scriptJob(event=["timeChanged", display_message_at_current_time])

# Example usage:
file_path = "your file path goes here"
read_strings_from_file(file_path)

# Trigger the function initially to display the message for the current frame
display_message_at_current_time()

Replies

Sign In or Register to comment.