RuntimeInitializeOnLoad

Custom attribute that forces static constructor execution for marked classes at application startup. Scans all Paragon assemblies via reflection and calls RuntimeHelpers.RunClassConstructor for each decorated type.

Definition

Namespace: Paragon Assembly: Paragon.dll

[AttributeUsage(AttributeTargets.Class)]
public class RuntimeInitializeOnLoadAttribute : Attribute

Inheritance: AttributeRuntimeInitializeOnLoadAttribute

Remarks

Unity's built-in [RuntimeInitializeOnLoadMethod] attribute works on static methods — it calls a specific method at startup. However, there is no built-in way to force a static constructor (class initializer) to run at startup for static classes.

RuntimeInitializeOnLoadAttribute fills this gap. It provides a class-level attribute that, combined with a [RuntimeInitializeOnLoadMethod] bootstrap method inside the attribute itself, forces all marked classes to have their static constructors executed during application initialization.

How It Works

  1. The Initialize() method is decorated with Unity's [RuntimeInitializeOnLoadMethod], so Unity calls it automatically at startup

  2. Initialize() scans all loaded assemblies whose name starts with "Paragon"

  3. For each assembly, it finds all types decorated with [RuntimeInitializeOnLoad]

  4. For each matching type, it calls RuntimeHelpers.RunClassConstructor(type.TypeHandle), which executes the type's static constructor if it hasn't already run

Why This Exists

Static classes with initialization logic (e.g., ParagonPaths) need their static constructors to run before any code references them. Without this attribute, a static constructor only runs when the class is first accessed — which may be too late if initialization order matters.

By marking a class with [RuntimeInitializeOnLoad], you guarantee its static constructor runs during the application startup phase, before gameplay code executes.

Quick Lookup

Goal
How

Force static ctor at startup

Decorate class with [RuntimeInitializeOnLoad]

Scope

Only scans assemblies starting with "Paragon"

Mechanism

RuntimeHelpers.RunClassConstructor(type.TypeHandle)

Trigger

Unity's [RuntimeInitializeOnLoadMethod] on the internal Initialize() method

Methods

Initialize (private static)

Bootstrap method called by Unity at startup. Scans Paragon assemblies and forces static constructors.

Algorithm:

Common Pitfalls

circle-exclamation
circle-exclamation
circle-exclamation
circle-exclamation
circle-info

Idempotent RuntimeHelpers.RunClassConstructor is safe to call on a type whose static constructor has already run — it becomes a no-op. There is no risk of double-initialization.

Examples

Basic Usage

Static Service Registration

Comparison with Unity's Built-in Attribute

See Also

Last updated