unity-game-engineassembliesbuilding

How to exclude UnityEditor reference from asmdef?


How to exclude UnityEditor reference from asmdef?

Why I need it:

I have an asmdef file. For example, it is MyAssembly/MyAssembly.asmdef. The MyAssembly contains a lot of features and each feature staff is placed in its own folder. And some of these features has a code that is needed only in editor, and it refers to UnityEditor namespace. Such editor code is placed into an Editor folder.

But as you know, Editor folder name means nothing in terms of asmdef usage. So I add AssemblyDefenitionReference in each folder and refer it to the MyAssemblyEditor.asmdef assembly definition. So the paths looks like this:

All this works good. But the problem is that, when some developer adds a new feature, he can forget to add a reference to the MyAssemblyEditor.asmdef in the editor folder. And there are no any errors will be shown in this case. This mistake will be revealed only when the build will be cooked. But I'd like that using of UnityEditor in MyAssembly will be instantly marked as an error.

Feel free to suggest other solution for this problem.


Solution

  • This thread got me thinking I can use CsprojPostprocessor to remove all references to UnityEditor from my csproj file. I wrote such class:

    using System.Text.RegularExpressions;
    using UnityEditor;
    
    // ReSharper disable once CheckNamespace
    public class CsprojPostprocessor : AssetPostprocessor
    {
        
        public static string OnGeneratedCSProject(string path, string content)
        {
            if (!path.EndsWith("Editor.csproj") && !path.EndsWith("Tests.csproj"))
            {
                var newContent = 
                    Regex.Replace(content, "<Reference Include=\"UnityEditor(.|\n)*?</Reference>", "");
    
                return newContent;
            }
    
            return content;
        }
    }
    

    It also can be done with an xml parser or something.

    The only thing, that confuse me is that this mechanism is badly documented and doesn't look like something simple users should use. So I use it at my own risk, but looks like there is no guarantee it will be strongly supported in future.