+2 votes

I need to store a lot of text for my game. I also need to be able to edit it in-editor. The obvious solution to this is text files, but I can't seem to get them to work in Godot.

My first thought was to create a new resource, and make it a text file. This gave me a .tres file which acted as a text file. This was fine, until the contents of the file deleted themselves, and were replaced with "[resource]". Or, until Godot forgot that it was a text file, and tried to open it as a scene.

new resource panel, with TextFile selected

Then I thought I'd use a txt file, but Godot just wouldn't let me import that at all. After some research I tried a .csv file, and while it was imported, it couldn't be edited in-editor, and filled the console with errors.

So, how do I import a text file that I can change in-editor? Is this even possible?

in Engine by (25 points)

1 Answer

+7 votes

Basically what you want to do is load a file and read its content. You can do that by placing a .txt file in your project folder. Then you store the file's path in a variable named "file". Then you need to open said file and do whatever you want with its content. The following example opens a specified file, goes though it line by line and prints out each line unitl the end of the file is reached.

extends Node2D

onready var file = 'res://foobar.txt'

func _ready():
    load_file(file)

func load_file(file):

    var f = File.new()
    f.open(file, File.READ)
    var index = 1
    while not f.eof_reached(): # iterate through all lines until the end of file is reached
        var line = f.get_line()
        line += " "
        print(line + str(index))

        index += 1
    f.close()
    return

Place the above code in your main node or wherever you think is necessary. I hope this helps.

by (1,888 points)

This works, but when I export the project to Android, the text file isn't bundled it seems and I get a read error :(
The text file doesn't have a corresponding .import file and I'm not sure how to create one... Not sure if that's the reason why it doesn't get bundled in the final APK.

When I get to the get_line, it comes back with a NULL value after a bit of a pause. The file is big (360M), could this be too big for this function to read?

var line = f.get_line()
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.