Here’s a minimal, decoupled C# implementation for Godot 4 that shows a browsable file‐system tree with selectable files/folders, emitting signals for each, and supports per‑extension icons. The code is split into four small classes:
- FileSystemEntry – a simple data struct
- DirectoryScanner – scans a single directory level
- FileIconProvider – a
Resource you can assign in the inspector to map extensions (and folders) to icons
- FileSystemBrowser – a
Control that builds a Tree, populates items recursively, and emits FileSelected/DirectorySelected
File: FileSystemEntry.cs
namespace FileBrowser
{
/// <summary>
/// Represents a single entry (file or directory) in the file system.
/// </summary>
public struct FileSystemEntry
{
public string Name { get; }
public string Path { get; }
public bool IsDirectory { get; }
public FileSystemEntry(string name, string path, bool isDirectory)
{
Name = name;
Path = path;
IsDirectory = isDirectory;
}
}
}
File: DirectoryScanner.cs
using Godot;
using System.Collections.Generic;
namespace FileBrowser
{
/// <summary>
/// Scans one level of a directory and returns its immediate children.
/// </summary>
public static class DirectoryScanner
{
public static IEnumerable<FileSystemEntry> Scan(string directoryPath)
{
var dir = DirAccess.Open(directoryPath);
if (dir == null)
yield break;
// second arg true => skip hidden files
dir.ListDirBegin(skipNavigational: true, skipHidden: false);
while (true)
{
string name = dir.GetNext();
if (string.IsNullOrEmpty(name))
break;
bool isDir = dir.CurrentIsDir();
string fullPath = $"{directoryPath}/{name}";
yield return new FileSystemEntry(name, fullPath, isDir);
}
dir.ListDirEnd();
}
}
}
File: FileIconProvider.cs
using Godot;
using Godot.Collections;
namespace FileBrowser
{
[Tool]
public partial class FileIconProvider : Resource
{
[Export] public Texture2D DefaultFileIcon { get; set; }
[Export] public Texture2D DefaultFolderIcon{ get; set; }
/// <summary>
/// Maps file‐extension (without dot) → icon.
/// </summary>
[Export] public Dictionary<string, Texture2D> ExtensionIcons { get; set; } = new();
/// <summary>
/// Returns the appropriate icon for a path.
/// </summary>
public Texture2D GetIcon(string path, bool isDirectory)
{
if (isDirectory)
return DefaultFolderIcon;
string ext = System.IO.Path.GetExtension(path)
?.TrimStart('.')
.ToLowerInvariant();
if (!string.IsNullOrEmpty(ext) && ExtensionIcons.TryGetValue(ext, out var ico))
return ico;
return DefaultFileIcon;
}
}
}
File: FileSystemBrowser.cs
using Godot;
using Godot.Collections;
namespace FileBrowser
{
/// <summary>
/// Control that shows a recursive file‐system tree and emits:
/// FileSelected(path) or DirectorySelected(path)
/// on item activation (double‐click / Enter).
/// </summary>
public partial class FileSystemBrowser : Control
{
[Export(PropertyHint.Dir)]
public string RootPath { get; set; } = "res://";
[Export]
public FileIconProvider IconProvider { get; set; }
[Signal] public delegate void FileSelectedEventHandler(string path);
[Signal] public delegate void DirectorySelectedEventHandler(string path);
private Tree _tree;
public override void _Ready()
{
// Create/configure Tree
_tree = new Tree
{
SizeFlagsHorizontal = (int)SizeFlags.FillExpand,
SizeFlagsVertical = (int)SizeFlags.FillExpand
};
AddChild(_tree);
_tree.Connect("item_activated", new Callable(this, nameof(OnItemActivated)));
BuildTree();
}
/// <summary>
/// Clears then populates the Tree from RootPath.
/// </summary>
private void BuildTree()
{
_tree.Clear(); // wipe any existing items
var rootItem = _tree.CreateItem(); // invisible root
PopulateTreeItems(rootItem, RootPath);
}
/// <summary>
/// Recursively scans `directoryPath` and adds children under `parent`.
/// </summary>
private void PopulateTreeItems(TreeItem parent, string directoryPath)
{
var entries = new List<FileSystemEntry>(DirectoryScanner.Scan(directoryPath));
// Sort: directories first, then files; both alphabetically
entries.Sort((a, b) =>
{
if (a.IsDirectory != b.IsDirectory)
return a.IsDirectory ? -1 : 1;
return a.Name.CompareTo(b.Name);
});
foreach (var e in entries)
{
var item = _tree.CreateItem(parent);
item.SetText(0, e.Name);
// store both path & isDirectory in metadata
var meta = new Dictionary { ["path"] = e.Path, ["isDir"] = e.IsDirectory };
item.SetMetadata(0, meta);
// optional icon
var icon = IconProvider?.GetIcon(e.Path, e.IsDirectory);
if (icon != null)
item.SetIcon(0, icon);
// recurse into directories
if (e.IsDirectory)
PopulateTreeItems(item, e.Path);
}
}
/// <summary>
/// Called on double‐click or Enter. Emits the appropriate signal.
/// </summary>
private void OnItemActivated(TreeItem item)
{
var meta = item.GetMetadata(0) as Dictionary;
if (meta == null)
return;
string path = (string)meta["path"];
bool isDir = (bool)meta["isDir"];
if (isDir)
EmitSignal(nameof(DirectorySelected), path);
else
EmitSignal(nameof(FileSelected), path);
}
}
}
Usage:
- Create a new
Control scene, attach FileSystemBrowser.cs as its script.
- In the inspector, set RootPath and assign a FileIconProvider (you can make one via “New Resource”).
- Connect its
FileSelected(path) and DirectorySelected(path) signals to your logic.
All methods are small and single‑purpose, each class does only what it needs, and the icons are fully customizable per extension and for folders. 🚀