How to create a BuildOptions mask in the Editor Window?

I’m trying to setup an EditorWindow script that can create separate builds. So far everything is going well and works. The only issue I seem to be having is setting up a BuildOptions mask in the editor.

I want to have code that does something like this:

private int buildOptionsMask = 0;
private void OnGUI()
{
     buildOptionsMask = (int)((BuildOptions)EditorGUILayout.EnumMaskField(
     (BuildOptions)buildOptionsMask));
     
     BuildPipeline.BuildPlayer(sceneNames, pathToBuildTo, 
     buildTarget, (BuildOptions)buildOptionsMask);
}

Thus, I was wondering how would we setup a BuildOptions mask that correctly uses the values picked in the mask. Currently, the code I posted does not work.

EDIT:
Dmitriy Yukhanov found a bug with Unity’s BuildOptions, so to correctly implement the mask the way it is suppose to be please see his comment here.

Hey, just do it like this:

private BuildOptions buildOptionsMask;
// ...
buildOptionsMask = (BuildOptions)EditorGUILayout.EnumMaskField(buildOptionsMask);

So your full snippet would be:

private BuildOptions buildOptionsMask = 0;
private void OnGUI()
{
	buildOptionsMask = (BuildOptions)EditorGUILayout.EnumMaskField(buildOptionsMask);
	BuildPipeline.BuildPlayer(sceneNames, pathToBuildTo, buildTarget, buildOptionsMask);
}

Well, EnumMaskField doesn’t quite do what you would expect. What it does is this:

string[] flagNames = (
    from x in Enum.GetNames(enumValue.GetType())
    select ObjectNames.NicifyVariableName(x)).ToArray<string>();
int value = MaskFieldGUI.DoMaskField(position2, controlID, Convert.ToInt32(enumValue), flagNames, style);
return EditorGUI.EnumFlagsToInt(type, value);

EnumFlagsToInt just does this:

private static Enum EnumFlagsToInt(Type type, int value)
{
    return Enum.Parse(type, value.ToString()) as Enum;
}

So it doesn’t really care about the actual values of the enum members. It just shows the enum member names in the order they are returned by “Enum.GetNames” and treat them as 1,2,4,8,16, … regardless of their actual value.

That’s why i wrote this wrapper a long time ago. It should work with all bitflag enums and will also handle “combined” values like:

public enum EAbility
{
    Fly = 0x02,
    Swim = 0x04,
    Walk = 0x08,
    Talk = 0x10,
    Sleep = 0x20,

    FlyAndSwim = 0x06,
    WalkAndTalk = 0x18,
    AllWithoutSleep = 0x1E
}

Note: I skipped 0x01 on purpose. Gaps aren’t a problem for that method.