3

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.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Aiden Faulconer
  • 411
  • 1
  • 7
  • 18

3 Answers3

2

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.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • Thank you, although not practical here. Its very good to know if ever I run into a situation where this is clean and easy. Cheers! – Aiden Faulconer Jul 10 '19 at 03:55
1

What about the ternary operator. Something like this:

return script.isPopup ? "Popup" : "Change Scene";

This could be also helpful https://stackoverflow.com/a/38451083/2946329

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
1

How about using ternary operator? instead of ()=>{ if (script.isPopup) { return "Popup" } else { return "Change Scene"} } use ((script.isPopup) ? "Popup" : "Change Scene").
Also you can use delegates

Sohaib Jundi
  • 1,576
  • 2
  • 7
  • 15