I'm creating a styling system for my UI with a set of StyleRule's for each UI type. Such as an ImageStyleRule
in which you can set what image to show, with what color etc. Every property also needs to be optional, or Overridable
. Leaving the property null isnt enough because in that case i cannot distinguish between set-this-field-to-null and leave-this-field-alone.
My setup looks like this:
public class Overridable<T>
{
public T Value;
public bool Override;
}
public class ImageStyleRule : StyleRule<Image>
{
private Overridable<Sprite> sprite = null, overrideSprite = null;
private Overridable<Color> color = null;
private Overridable<Material> material = null;
public override void ApplyRule(Image element)
{
base.ApplyRule(element);
if (sprite.Override)
element.sprite = sprite.Value;
if (overrideSprite.Override)
element.overrideSprite = overrideSprite.Value;
if (color.Override)
element.color = color.Value;
if (material.Override)
element.material = material.Value;
}
}
As you can see the ApplyRule
method contains a lot of duplicate code, and i'd really like to avoid that. I think i need a method like this: setOverride(*element.sprite, sprite)
where i pass in the field and a reference to the Overridable and it magically sets the right reference.
I've tried passing by reference, and using pointers but none work. Reflection would be too slow for my use case. Is there any other way to solve this issue?
Thanks in advance!