Extending the Unity3D Color struct

I’m working on a convenience class that will allow me to specify the color used by an NGUI item by the SVG/HTML named color list (http://www.december.com/html/spec/colorsvg.html).

I was hoping I could extend the standard Unity3D Color class by adding a static method that could be used to update the color values, however as Color is a struct and not a class, you can’t update the value in an extension method as a copy is passed.

    public static void ColorWithName(this Color color,
     PBColor.ColorNames name)
    {
        color = PBColor.FromName(name);
    }

This will not work as expected.  The var color points to a copy of the calling color struct and not the actual struct, so any changes are discarded 🙁

I ended up with this:

    public static void ColorWithName(this UIWidget widget,
     PBColor.ColorNames name)
    {
        widget.color = PBColor.FromName(name);
    }

Not as convenient as I wanted, but it gets the job done as below:

    widget.ColorWithName(ColorNames.GoldenRod);

where widget is an NGUI.UIWidget object.

Leave a Reply