Skip to content

Instantly share code, notes, and snippets.

@LumosX
Last active September 18, 2023 12:39
Show Gist options
  • Save LumosX/9cde05c46956fbc705dcbb2d9b39e087 to your computer and use it in GitHub Desktop.
Save LumosX/9cde05c46956fbc705dcbb2d9b39e087 to your computer and use it in GitHub Desktop.
Helper functions for parsing dynamic list ports in the xNode open-source node editing framework for Unity.
// Example output ports and how we can use them:
[Output(dynamicPortList = true)]
public string[] stringOutputs;
[Output(dynamicPortList = true)]
public float[] floatOutputs;
public override object GetValue(NodePort port) {
// Boilerplate reduction: instead of parsing ports manually every single time, just "expose" a function for the index, if it matches
// You can even chain them with null coalescing in order to not check subsequent fields after one is found
this.WithDynamicListPort(port, nameof(stringOutputs), i => stringOutputs[i]) ??
this.WithDynamicListPort(port, nameof(floatOutputs), i => floatOutputs[i]);
}
///////////////////////////////////////////////////////
// And somewhere else... (C# 7!)
public static class NodeExtensions {
// ReSharper disable once SuggestBaseTypeForParameter, MemberCanBePrivate.Global
public static int GetDynamicListPortIndex(this Node caller, NodePort port, string prefix) {
if (port.node != caller) return -1; // you may or may not want this depending on what you want with this
var success = int.TryParse(port.fieldName.Split(' ')[1], out var result);
return port.fieldName.StartsWith(prefix) && success ? result : -1;
}
public static object WithDynamicListPort(this Node caller, NodePort port, string prefix, Func<int, object> function) {
var index = caller.GetDynamicListPortIndex(port, prefix);
return index == -1 ? null : function(index);
}
public static T WithDynamicListPort<T>(this Node caller, NodePort port, string prefix, Func<int, T> function) {
var index = caller.GetDynamicListPortIndex(port, prefix);
return index == -1 ? default : function(index);
}
}
@Dullame
Copy link

Dullame commented Sep 18, 2023

Thank you! It was a big help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment