31 / GodotOnReady

A C# Source Generator that adds convenient onready-like features to your C# scripts in Godot Mono (3.x) without any reflection.
https://www.nuget.org/packages/GodotOnReady
MIT License
123 stars 13 forks source link

Add enum to data mapping generator #2

Closed 31 closed 3 years ago

31 commented 3 years ago

This isn't really OnReady functionality... but I've seen this asked about twice before and it ties into the Godot limitation where the only way you can export a set of options to show up in the editor is via enum (or I suppose an editor plugin).

From the data definitions:

[GenerateDataSelectorEnum("Tag")]
public partial class TagData
{
    private static readonly TagData A = new() { Name = "Table" };
    private static readonly TagData B = new() { Name = "Chair" };
    private static readonly TagData C = new() { Name = "Rug" };

    public string Name { get; set; }
}

Generate a lookup and enum:

public enum Tag { A, B, C }

public class TagData
{
    public static TagData Get(Tag tag)
    {
        switch (tag)
        {
            case Tag.A: return A;
            case Tag.B: return B;
            case Tag.C: return C;
        }
        return null;
    }
}

This way you can [Export] Tag Foo to give the scene editor a choice between several options, with an easy (and efficient) way to attach more data to each of those options.

31 commented 3 years ago

Ended up with:

public partial class DemoEnumData
{
    private static readonly DemoEnumData
        A = new DemoEnumData
        {
            Extended = "AaaaaAAaaAAAAA"
        },
        B = new DemoEnumData
        {
            Extended = "BbbbbBbbbbbb"
        };

    public string Extended { get; private set; }
}
public partial class DemoEnumData
{
    public static DemoEnumData Get(DemoEnum key)
    {
        switch (key)
        {
            case DemoEnum.A: return A;
            case DemoEnum.B: return B;
        }
        throw new ArgumentOutOfRangeException("key");
    }
}

public enum DemoEnum
{
    A,
    B,
}
public static class DemoEnumExtensions
{
    public static DemoEnumData GetData(this DemoEnum v) => DemoEnumData.Get(v);
}