-->

分類

2018年7月25日 星期三

[Unity] Modify project define symbols when executing scripts in -batchmode

Sometimes you need to add/remove project define symbols to achieve conditional compilation.

When the Unity Editor is running in GUI mode, this can be done by calling PlayerSettings.SetScriptingDefineSymbolsForGroup, but this trick doesn't work when you run Unity Editor in batch mode.

To modify the define symbols in batch mode, we need to modify the ProjectSettings by SerializedObject class.

Here is the example for modifying define symbols for standalone platform:

    string ProjectSettingsAssetPath = "ProjectSettings/ProjectSettings.asset";
    SerializedObject projectSettingsManager = new SerializedObject(UnityEditor.AssetDatabase.LoadAllAssetsAtPath(ProjectSettingsAssetPath)[0]);
    SerializedProperty scriptingDefineSymbols = projectSettingsManager.FindProperty("scriptingDefineSymbols");
    SerializedProperty standaloneDefineSymbols = scriptingDefineSymbols.GetArrayElementAtIndex(0);//standalone platform is at index 0
    standaloneDefineSymbols = standaloneDefineSymbols.FindPropertyRelative("second");
    AddOrRemoveDefineSymbols(standaloneDefineSymbols, true, "YOUR_DEFINE_SYMBOL");

    public void AddOrRemoveDefineSymbols(SerializedProperty standaloneDefineSymbols, bool add, string defineSymbol)
    {
        string defineSymbolsValue = standaloneDefineSymbols.stringValue;
        List defineStrings = new List(defineSymbolsValue.Split(';'));
        if(add)
        {
            if (defineStrings.Contains(defineSymbol)) { return; }
            defineStrings.Add(defineSymbol);
            standaloneDefineSymbols.stringValue = string.Join(";", defineStrings.ToArray());
            projectSettingsManager.ApplyModifiedProperties();
        }
        else
        {
            if (!defineStrings.Contains(defineSymbol)) { return; }
            defineStrings.Remove(defineSymbol);
            standaloneDefineSymbols.stringValue = string.Join(";", defineStrings.ToArray());
            projectSettingsManager.ApplyModifiedProperties();
        }
    }



You can check the file "ProjectSettings.asset" to investigate the data structure:


沒有留言:

張貼留言