Null Salad
Null Salad

Reputation: 1030

how do you load a text file in Godot 3.5?

I am trying to load a .json text file. It works fine in desktop preview but when I try and test on Android this does not work.

Approach 1 - using System.IO.File:

  string filePath = @"./Story/ChatStories/branching_dialogue.json";
  if (!File.Exists(filePath)) GD.Print("cannot find file!");
  string text = File.ReadAllText(filePath);
  GD.Print(text);

✅ works on desktop preview

❌ does not work on Android preview, Android export, HTML5, or Windows export.

Approach 2 - using Godot.File

  string filePath = @"res://Story/ChatStories/branching_dialogue.json";
  File file = new File();
  file.Open(filePath, File.ModeFlags.Read);
  string text = file.GetAsText();        
  file.Close();
  GD.Print(text);

✅ works on desktop preview

❌ does not work on Android preview, Android export, HTML5, or Windows export.

Engine level things I've tried:

How do you load a silly little text file?

Upvotes: 2

Views: 983

Answers (1)

Theraot
Theraot

Reputation: 40315

The problem is not the path, the problem is that the file is not anywhere. It works on desktop when launching from the editor, because in that case res:// is mapped to the real project folder. But once exported (yes, even on desktop) the imported resources are packaged (by default in a .pck file) and the res:// references to files in that package...

So if the text file is not an imported resource, it is not in the exported game, in any platform, at all.

This is supposed to be fixed by telling Godot to include the file in the export presets. Try that, although last time I tried it didn't work...

What I would suggest to do is to crate an import plugin which you can have import the text file as a custom resource, which you can then load like any other resource in your game.

To be clear, once text file is imported as a resource, it will have a res:// path, which in the exported game are packaged inside a file. Thus, System.IO.File cannot get it. So you will use Godot's API for this instead.

Upvotes: 1

Related Questions