Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starikcetin/05af27f10ff0d87981ec3eb954e17a54 to your computer and use it in GitHub Desktop.
Save starikcetin/05af27f10ff0d87981ec3eb954e17a54 to your computer and use it in GitHub Desktop.
Running Code at Unity Editor Launch Before Scripts Compile

Create a standalone pure C# project.

Create a Directory.Build.props right alongside your .csproj file:

<Project>
    <PropertyGroup>
        <UnityProjectPath>$(MSBuildProjectDirectory)\relative_path_to_unity_project\</UnityProjectPath>
    </PropertyGroup>
</Project>

Add these to your .csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <!-- these might look different on your end, depending on which Unity version you are targeting -->
  <PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  
  <!-- gets this nuget package: https://github.com/Rabadash8820/UnityAssemblies -->
  <ItemGroup>
    <PackageReference Include="Unity3D" Version="2.1.3" />
  </ItemGroup>
  
  <!-- allows using UnityEditor namespace -->
  <ItemGroup>
    <Reference Include="$(UnityEditorPath)" Private="false" />
  </ItemGroup>
  
  <!-- copies DLL to unity project right after building this c# project -->
  <Target Name="CopyDLLToUnity" AfterTargets="Build">
    <Message Text="Copying DLL to Unity project" Importance="High" />
    <Copy
      SourceFiles="$(TargetDir)$(ProjectName).dll"
      DestinationFolder="$(MSBuildProjectDirectory)\relative_path_to_unity_project\Assets\Plugins\Editor\"
    />
  </Target>
</Project>

Create this:

[InitializeOnLoad]
public static class RunBeforeScriptsCompile
{
    static RunBeforeScriptsCompile()
    {
        // Code to run before scirpt compilation here.
    }
}

Build and create a DLL.

Copy DLL to Assets/Plugins/Editor (you don't have to if you included the auto-copy to your .csproj file).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment