Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C#: Inline bulk edit a class, possible?

using C# (Unity), just wondering if it’s possible to bulk edit a class inline using something like this:

transform.Find("Difficulty/3").GetComponent<Button>()=>{
    this.interactible = true;
    this.color = SStatusEffect;
    this.blahblah = whatever;
}
transform.Find("Difficulty/5").GetComponent<Button>()=>{
    this.interactible = true;
    this.color = SStatusEffect;
    this.blahblah = whatever;
}

I know it’s possible to do inline functions for events and stuff, but is this sort of thing possible?

Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Just looking for an alternative to this as it gets tedious in larger/complex scenarios.

transform.Find("Difficulty/5").GetComponent<Button>().interactible = true;
transform.Find("Difficulty/5").GetComponent<Button>().color = SStatusEffect;
transform.Find("Difficulty/5").GetComponent<Button>().blahblah = whatever;

or this

Button but = transform.Find("Difficulty/3").GetComponent<Button>();
but.interactible = true;
but.color = SStatusEffect;
but.blahblah = whatever;

>Solution :

You can get something like what you want with an extension method, like so:

static class Extensions
{
    public static void Mutate<T>(this T obj, Action<T> mutations) =>
        mutations(obj);
}

And you call it like:

transform.Find("Difficulty/5").GetComponent<Button>().Mutate(o => {
    o.interactible = true;
    o.color = SStatusEffect;
    o.blahblah = whatever;
});

Though I personally don’t find (hehe, get it? find?) that much more readable than the regular if-let pattern:

if(transform.Find("Difficulty/5").GetComponent<Button>() is {} button)
{
    button.interactible = true;
    button.color = SStatusEffect;
    button.blahblah = whatever;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading