Editing assemblies during build process

Hello everyone,

I hope you are all doing well. For my personal project, I’m working on a tool that should be able to edit assemblies during the build process and use these edited assemblies when building the game, without modifying the original scripts in the Assets folder.

I’ve made progress and created a script that edits the necessary assemblies in the Library/ScriptAssemblies folder. However, the changes made by the script are not reflected in the built game.

MenuItem("Window/Build")]
public static void CustomBuild()
{
// Required modifications for the assemblies.
  OptimizeAssemblies();
                   
// Start build process manually.
  BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
  buildPlayerOptions.scenes = EditorBuildSettings.scenes.Select(scene => scene.path).ToArray();
  buildPlayerOptions.locationPathName = "Builds/Windows/MyGame.exe";
  buildPlayerOptions.target = BuildTarget.StandaloneWindows64;
  buildPlayerOptions.options = BuildOptions.None;
  BuildPipeline.BuildPlayer(buildPlayerOptions);      
           
}


private  static void OptimizeAssemblies()
{

Directory.CreateDirectory(tempDir);

// Get all player assemblies
var assemblies = CompilationPipeline.GetAssemblies(AssembliesType.Player);
           
foreach (var assembly in assemblies)
{
                if (assembly.name.Contains("Assembly-CSharp"))
                {
                    var assemblyPath = assembly.outputPath;
                    var tempAssemblyPath = Path.Combine(tempDir, Path.GetFileName(assemblyPath));
                    File.Copy(assemblyPath, tempAssemblyPath, true);
                    var assemblyDef = AssemblyDefinition.ReadAssembly(tempAssemblyPath);
                    OptimizationManager.OptimizeAssemblyDefinition(assemblyDef);
                    assemblyDef.Write(assemblyPath);
                }
            }
        }

Likely because after making those changes you’d have to perform a script compilation.

May I ask what that “optimization” is about?
I have a hunch you’re trying to do something that isn’t necessary, or could be done in a different, less intrusive way.

It also looks fishy to me since you try to modify the assembly definition of all scripts that don’t have an assembly definition. Perhaps instead you may want to create those assembly definitions so that there is nothing in “Assembly-CSharp” to begin with?

Lastly, looping over all assemblies is the opposite of “optimized”. Use the TypeCache instead.

I don’t know what kind of “optimization” you want to do at assembly level, do you want to modify the source code during the compilation?

Maybe you are looking for Source Generators? Source Generators - C# | Microsoft Learn