Topic was automatically imported from the old Question2Answer platform.
Asked By
Setherino
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.
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?
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.
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.
endavid | 2022-03-20 21:03
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?
Note: You cannot access a text file with a resource path in the exported project, unless you add a filter *.txt to “Filters to export non-resoucre files/folders” under Project → Export → Resources tab.