OnCodeLoadedAttribute
Marks a static method as a callback to be invoked after code has been loaded during Editor startup or after a code reload.
Read time 4 minutesLast updated 5 days ago
Definition
- Type: Class
- Namespace: Unity.Scripting.LifecycleManagement
- Assembly: Unity.Scripting
- Inherits from: LifecycleAttributeBase
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]public sealed class OnCodeLoadedAttribute : LifecycleAttributeBase
Remarks
Methods marked with this attribute are called after assemblies have been loaded and initialized. This happens:
- After initial code load (Editor and Player).
- After a code reload (Editor only).
Use this callback to:
- Perform type discovery using TypeCache or reflection.
- Initialize caches that depend on loaded types.
- Set up references to types from other assemblies.
This is a method attribute that can only be applied to methods with no parameters and return type .
staticvoidAdditional Resources: OnCodeUnloadingAttribute, OnCodeInitializingAttribute, RuntimeInitializeOnLoadMethodAttribute, InitializeOnLoadAttribute
Examples
using Unity.Scripting.LifecycleManagement;using UnityEngine;using System;using System.Collections.Generic;public static partial class PluginRegistry{ private static Dictionary<string, Type> s_PluginTypes; [OnCodeLoaded] static void DiscoverPlugins() { s_PluginTypes = new Dictionary<string, Type>(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { foreach (var type in assembly.GetTypes()) { var attr = type.GetCustomAttributes(typeof(GamePluginAttribute), false); if (attr.Length > 0) s_PluginTypes[type.Name] = type; } } } public static Type GetPlugin(string name) => s_PluginTypes.TryGetValue(name, out var t) ? t : null;}public class GamePluginAttribute : Attribute { }
Constructors
Constructor | Description |
|---|---|
| OnCodeLoadedAttribute() | Marks the decorated static method to be invoked after all assemblies have been loaded during Editor startup or after a code reload. |