Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using In-Line Lambda functions as an argument

I am optionally display some content in the Unity Editor based on options chosen for a given component, this will be used when displaying a summary of options chosen on this current Component.

How I can make a function inline that returns a string, I want this function to be inline because there will be many of these and they will only useful in the line they are used in.

I have provided a code snippet that may clarify what I am trying to do.

I have used lambda functions like this in c++ and JavaScript, but not in c# and I've tried finding an answer on how to use them like this in C#.

var script = target as ButtonManager;//get reference to this Component 

EditorGUILayout.LabelField("Your current Interactive configuration", 
            "Parent: " + script.sceneParent.name + "\n",
            "Popup? " + ()=>{ if (script.isPopup) { return "Popup" } else { return "Change Scene"} }
            + "\n"
            );

Edit: I can use a ternary operator to solve this problem, but I am curious as to how this would work with lambda functions.

like image 313
Aiden Faulconer Avatar asked May 16 '26 20:05

Aiden Faulconer


1 Answers

To use a delegate inline in your string concatenation you need to create a new Func<string> from the anonymous method and execute it:

EditorGUILayout.LabelField("Your current Interactive configuration", 
            "Parent: " + script.sceneParent.name + "\n",
            "Popup? " + new Func<String>(()=>{ if (script.isPopup) { return "Popup"; } else { return "Change Scene";} })()
            + "\n"
            );

yuk. You also need to consider things like variable closure. All that to say that the ternary operator is a cleaner solution here.

like image 136
D Stanley Avatar answered May 18 '26 09:05

D Stanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!