0 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?

asked Dec 15, 2019 in Engine by Setherino (19 points)

1 Answer

+2 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.

answered Dec 15, 2019 by johnygames (1,576 points)
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 How to use this Q&A? before posting your first questions.