Search code examples
c#unity-game-engineinlineeditbulk

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!

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;
    }