I have seen people discussing how to create consistent text file resources that are user friendly in the editor. This is the simplest solution I could think of.
This is purposefully as dead simple as possible so it can be expanded on for your project.
It allows you set text files as resource by path while allowing you to edit the text in the built-in text editor, or an external editor. I also threw in a quick template engine.
TextFileResource
using System;
using System.Collections.Generic;
using Godot;
[GlobalClass]
public partial class TextFileResource : Resource
{
[Export]
private string File = "res://text_resource.txt";
private string content = null;
public void LoadFile()
{
try{
var file = FileAccess.Open(File, FileAccess.ModeFlags.Read);
content = file.GetAsText();
} catch (Exception e)
{
GD.PrintErr("Error loading text file resource: " + File + " " + e.Message);
}
}
public string GetContent()
{
if(content == null)
{
LoadFile();
}
return content;
}
public string RenderTemplate(Dictionary<string, string> variables)
{
if(content == null)
{
LoadFile();
}
string renderedOutput = content;
foreach(KeyValuePair<string, string> variable in variables)
{
renderedOutput = renderedOutput.Replace("{" + variable.Key + "}", variable.Value);
}
return renderedOutput;
}
}
How to use
These examples are in C# but they will work in GDScript. I will let you do the conversion.
- Add to your script
[Export]
private TextFileResource FileResource;
- Add script to node.
- Select node.
- In Inspector, create “New TextFileResource”.
- In FileSystem panel, right click desired text File, “Copy Path”
- Back in Inspector, paste path into File field of the TextFileResource created in 4.
- Access the file contents
string content = FileResource.GetContent();
Templates
Text File
{name},
The message of the day is: {message}
Usage
string renderedContent = FileResource.RenderTemplate(new Dictionary<string, string>{
{"name", "Nick"},
{"message", "Hello World!"}
});
Output
Nick,
The message of the day is: Hello World!