Helpers and Source Generation¶
What Are Source Generators¶
Source generators are a C# feature (introduced in C# 9.0) that automatically write code for you at compile time. Think of them as smart code wizards that look at your code, see what you need, and generate the boilerplate automatically.
In plain English¶
- You write:
[DxAutoConstructor]on a struct - Source generator sees: "Oh, they want a constructor!"
- Source generator creates: A constructor with all the fields as parameters
- You get: Less typing, fewer bugs, more consistent code
Learn more about source generators¶
DxMessaging Attributes (Your Code Wizards)¶
The attributes live in WallstopStudios.DxMessaging.Attributes. Unity assembly definitions that use them must reference this assembly. Shared rules that only need constructors and optional arguments can enable noEngineReferences and omit the messaging runtime. Message generation still needs the runtime interfaces. See the 4.0 migration steps for existing assemblies.
Use the attributes below to declare message types, generate constructors, and set optional defaults:
1. Message Type Attributes (Pick Your Message Category)¶
These tell the source generator what KIND of message you're making:
[DxUntargetedMessage] - Global Messages¶
[DxUntargetedMessage] // <- Tells generator: "This is a global message"
public readonly partial struct GamePaused { }
What it generates¶
- Implements
IUntargetedMessage - Adds a
MessageTypeproperty for the concrete message type - Makes it work with
.Emit()extension methods
[DxTargetedMessage] - Messages to Specific Targets¶
[DxTargetedMessage] // <- Tells generator: "This goes to one specific target"
public readonly partial struct Heal {
public readonly int amount;
}
What it generates¶
- Implements
ITargetedMessage - Adds a
MessageTypeproperty for the concrete message type - Makes it work with
.EmitGameObjectTargeted()/.EmitComponentTargeted()
[DxBroadcastMessage] - Messages from a Source¶
[DxBroadcastMessage] // <- Tells generator: "This broadcasts from a source"
public readonly partial struct TookDamage {
public readonly int amount;
}
What it generates¶
- Implements
IBroadcastMessage - Adds a
MessageTypeproperty for the concrete message type - Makes it work with
.EmitGameObjectBroadcast()/.EmitComponentBroadcast()
2. [DxAutoConstructor] - Automatic Constructors¶
Apply [DxAutoConstructor] to a partial type to generate a constructor from its fields.
[DxUntargetedMessage]
[DxAutoConstructor]
public readonly partial struct VideoSettingsChanged
{
public readonly int width;
public readonly int height;
}
What you get (auto-generated)¶
// Generated constructor.
public VideoSettingsChanged(int width, int height)
{
this.width = width;
this.height = height;
}
Rules¶
- Creates constructor parameters in field declaration order within each source file
- Orders fields across partial files by the compiler's source-file order; use named arguments when that order is not controlled
- Includes
publicfields by default; opt in to serialized fields as described below - Ignores
staticfields - Works with
readonlystructs (recommended!) - Supports nested types inside partial classes, structs, and invariant interfaces
- Supports internal types (types with
internalvisibility)
Serialized fields and read-only properties (4.0.0)¶
Use IncludeSerializedFields = true to include declared instance fields marked with UnityEngine.SerializeField, at any accessibility. Set GenerateSerializedProperties = true to also generate their public read-only getters. The property option also enables those fields in the constructor; both options default to false.
For example, this handwritten form repeats its serialized field list:
using System;
using UnityEngine;
[Serializable]
public struct ScreenPrefab
{
[SerializeField] private int _screen;
[SerializeField] private GameObject _prefab;
public int Screen => _screen;
public GameObject Prefab => _prefab;
public ScreenPrefab(int screen, GameObject prefab)
{
_screen = screen;
_prefab = prefab;
}
}
Keep the type name and serialized field names, then add partial to generate the constructor and getters:
using System;
using DxMessaging.Core.Attributes;
using UnityEngine;
[Serializable]
[DxAutoConstructor(GenerateSerializedProperties = true)]
public partial struct ScreenPrefab
{
[SerializeField] private int _screen;
[SerializeField] private GameObject _prefab;
}
public static class ScreenPrefabExamples
{
public static ScreenPrefab Create(int screen, GameObject prefab)
{
return new ScreenPrefab(screen: screen, prefab: prefab);
}
}
The generated properties are Screen and Prefab. Serialized constructor parameters omit all leading underscores; property names uppercase the first remaining character using invariant casing. C# keyword parameter names are escaped, so _class becomes @class. Existing public fields that are not marked with SerializeField keep their parameter names.
To retain existing handwritten getters, enable only IncludeSerializedFields. Static fields, constants, and compiler-generated backing fields are excluded. The options select fields by the Unity attribute's full type name; an unrelated attribute called SerializeField does not opt in.
Keep serialized field names when migrating existing assets. Unity continues to serialize those fields, while generated getters add no storage. C# constructor calls apply optional defaults; Unity deserialization and default(T) keep their existing construction rules. DXMSG016 reports invalid names, duplicate parameter names, and property names that conflict with a type or an existing accessible member. Rename the conflicting field/member or keep explicit code. DXMSG017 reports field types that cannot appear in the generated public signatures. Make those types accessible or write the constructor and properties explicitly with suitable access levels.
Constructor restrictions¶
Fixed in v4.0.0: Generated constructors retain the required unsafe context for pointer parameters, preserve
void*syntax, and accept validnullpointer defaults. The consumer assembly must enable unsafe compilation. Function-pointer signatures also need support from your Unity version and scripting backend; the generator does not add that support.
Fixed in v4.0.0: Generated struct constructors also initialize excluded instance fields and auto-property backing storage to their type defaults. Existing field, auto-property, and field-like event initializers retain their values and execute once. For types without a primary constructor, user parameterless constructors are not invoked.
For example, this constructor takes only amount; PreviousAmount starts at zero:
using DxMessaging.Core.Attributes;
[DxAutoConstructor]
public readonly partial struct DamageState
{
public readonly int amount;
public int PreviousAmount { get; }
}
When compiling as C# 10, a struct that mixes initialized and uninitialized explicit-interface auto-properties with a user parameterless constructor needs an explicit choice. Add an initializer to every explicit-interface auto-property, use named backing fields, or remove [DxAutoConstructor] and write the constructor yourself. DXMSG011 identifies this combination. This restriction does not affect classes or C# 11 or later language versions. It does not change the supported Unity floor.
Fixed in v4.0.0: A type whose primary constructor takes parameters now receives DXMSG012 instead of an invalid generated secondary constructor. Remove [DxAutoConstructor] and write the constructor with an explicit this(...) chain to supply the primary constructor arguments. For an empty primary parameter list, the generator adds the required this() chain automatically. No diagnostic is needed when the type has no selected instance fields. Ordinary non-positional records and nested types inside positional containers remain supported.
Breaking change in v4.0.0: A record class with one selected field of its own record type receives DXMSG013. That constructor signature belongs to the record copy constructor. Earlier versions could silently change with results for sealed records. Remove [DxAutoConstructor] and use an init-only property with an object initializer, or write a construction API with a different signature. Ordinary classes and record constructors with other field types or multiple fields retain their behavior.
3. [DxOptionalParameter] - Optional Constructor Parameters¶
The DxOptionalParameterAttribute marks a field as optional when used with [DxAutoConstructor]. The source generator emits a constructor parameter with a default value for annotated fields, making it easy to create messages with sensible defaults.
How It Works with DxAutoConstructor¶
When you combine [DxOptionalParameter] with [DxAutoConstructor], the generator creates a constructor where:
- Required fields (without the attribute) become regular constructor parameters
- Optional fields (with the attribute) become parameters with default values
- Parameter order follows source-file compilation order, then field declaration order within each file
- C# rules apply - optional parameters must come after required parameters
[DxUntargetedMessage]
[DxAutoConstructor]
public readonly partial struct SettingsChanged
{
public readonly float volume; // Required (no attribute)
public readonly int quality; // Required (no attribute)
[DxOptionalParameter] // Optional, defaults to false
public readonly bool fullscreen;
[DxOptionalParameter(100)] // Optional, defaults to 100
public readonly int brightness;
}
Generated constructor¶
public SettingsChanged(float volume, int quality, bool fullscreen = default, int brightness = 100)
{
this.volume = volume;
this.quality = quality;
this.fullscreen = fullscreen;
this.brightness = brightness;
}
Calling the Constructor¶
Optional parameters support all standard C# calling conventions:
// Provide all arguments
var settings1 = new SettingsChanged(0.8f, 2, true, 80);
// Use all defaults
var settings2 = new SettingsChanged(0.8f, 2); // fullscreen=false, brightness=100
// Use named arguments to skip some optionals
var settings3 = new SettingsChanged(0.8f, 2, fullscreen: true); // brightness=100
var settings4 = new SettingsChanged(0.8f, 2, brightness: 50); // fullscreen=false
For a struct without an explicit parameterless constructor, new Message() and default(Message) initialize fields to zero, false, or null. They do not apply defaults from a generated constructor with optional parameters. Pass at least one argument, including a named argument, to select that constructor. A required field also makes this choice explicit at the call site.
Supported Default Value Types¶
The attribute provides constructor overloads for all common primitive types:
Info: Built-in Type Support
Numeric:
Category Types Signed Integers sbyte,short,int,longUnsigned Integers byte,ushort,uint,ulongFloating Point float,doubleOther:
Category Types Boolean boolCharacter charString stringFor enums, Unity types, and other complex types, use the
Expressionproperty.
Examples by type¶
[DxAutoConstructor]
public readonly partial struct TypeExamples
{
// Boolean
[DxOptionalParameter(true)]
public readonly bool isEnabled;
// Character
[DxOptionalParameter('X')]
public readonly char grade;
// String
[DxOptionalParameter("unknown")]
public readonly string playerName;
// Signed integers
[DxOptionalParameter((sbyte)-1)]
public readonly sbyte signedByte;
[DxOptionalParameter((short)100)]
public readonly short shortValue;
[DxOptionalParameter(42)]
public readonly int score;
[DxOptionalParameter(9999999999L)]
public readonly long bigNumber;
// Unsigned integers
[DxOptionalParameter((byte)255)]
public readonly byte level;
[DxOptionalParameter((ushort)1000)]
public readonly ushort maxHealth;
[DxOptionalParameter(50u)]
public readonly uint count;
[DxOptionalParameter(100UL)]
public readonly ulong totalPoints;
// Floating point
[DxOptionalParameter(1.5f)]
public readonly float speed;
[DxOptionalParameter(3.14159)]
public readonly double precision;
}
Using Type Defaults¶
When you use [DxOptionalParameter] without a value, the field defaults to the type's default value:
[DxAutoConstructor]
public readonly partial struct DefaultExamples
{
[DxOptionalParameter] // Defaults to 0
public readonly int count;
[DxOptionalParameter] // Defaults to false
public readonly bool isActive;
[DxOptionalParameter] // Defaults to null
public readonly string name;
[DxOptionalParameter] // Defaults to 0.0f
public readonly float multiplier;
}
Optional defaults follow C# implicit constant conversions. For example, [DxOptionalParameter(7)] sets a byte field's default, and [DxOptionalParameter(0)] sets an enum field's default. Values must fit the field type. The Expression property follows the same conversion rules. The supplied constant keeps its numeric type: [DxOptionalParameter(7)] can default a byte field, but [DxOptionalParameter(7.0)] cannot. The latter is a double constant.
Use constants such as float.NaN, double.PositiveInfinity, and double.NegativeInfinity as attribute arguments when these values are appropriate defaults. Signed zero keeps its sign.
Constructor parameters retain nullable field annotations, including nullable array and list elements. Fields declared with nullable annotations disabled retain that caller contract. Parameters from enabled contexts keep their nullable or nonnullable checks.
Changed in 4.0.0: Generated constructors retain nullable annotations and preserve valid constant conversions, numeric types, non-finite defaults, and signed zero.
Nullable value defaults¶
Use a nullable value type when an omitted value differs from zero. A null default leaves HasValue false; supplying zero keeps it true.
using DxMessaging.Core.Attributes;
[DxUntargetedMessage]
[DxAutoConstructor]
public readonly partial struct ProgressChanged
{
public readonly int total;
[DxOptionalParameter(null)]
public readonly int? completed;
}
public static class ProgressExample
{
public static void ShowDefaults()
{
ProgressChanged unknown = new ProgressChanged(10);
ProgressChanged zero = new ProgressChanged(10, completed: 0);
// unknown.completed.HasValue is false; zero.completed.HasValue is true.
}
}
[DxOptionalParameter(Expression = "null")] and the type default from [DxOptionalParameter] also leave a nullable value absent. An explicit null default on a nonnullable value type, such as int, produces DXMSG005.
Advanced: Custom Constant Expressions¶
Use the Expression property for compile-time constants that cannot be passed directly to an attribute constructor, such as enum values or named constants. The generator resolves the expression in the field's own declaration scope, including imports, aliases, and using static directives. It qualifies bound names for the generated file and preserves the original string returned by nameof. Ordinary C# optional-parameter rules still apply. Use [DxOptionalParameter] without an expression when a struct should use its default value.
Fixed in v4.0.0: Valid
nameof(...)defaults no longer abort constructor generation on Roslyn 5.9. Composed expressions keep their C# constant values and conversion rules.
using DxMessaging.Core.Attributes;
using UnityEngine;
public enum DamageType
{
Physical,
}
public static class GameConstants
{
public const int DefaultHealth = 100;
}
[DxAutoConstructor]
public readonly partial struct AdvancedDefaults
{
// Nullable types
[DxOptionalParameter(Expression = "null")]
public readonly int? optionalId;
// Enum values
[DxOptionalParameter(Expression = "DamageType.Physical")]
public readonly DamageType damageType;
// Structs use their default value
[DxOptionalParameter]
public readonly Vector3 position;
[DxOptionalParameter]
public readonly Color tint;
// Static constants
[DxOptionalParameter(Expression = "float.MaxValue")]
public readonly float range;
// Named constants from your code
[DxOptionalParameter(Expression = "GameConstants.DefaultHealth")]
public readonly int health;
// Symbol names
[DxOptionalParameter(Expression = "nameof(AdvancedDefaults)")]
public readonly string source;
}
💡 Tip: Expression rules
- Names resolve in the field's own source file, including when fields use different partial files
- Must be a valid C# constant expression
- Type safety is enforced by the C# compiler at build time
- Valid for enum members, literals, and named
constvalues- Runtime properties such as
DateTime.UtcNoworColor.whitecannot be optional parameter defaults
Code Examples¶
Example 1: Basic Optional Parameter with Default Value¶
[DxTargetedMessage]
[DxAutoConstructor]
public readonly partial struct Heal
{
public readonly int amount;
[DxOptionalParameter(false)]
public readonly bool isCritical;
}
// Usage:
var normalHeal = new Heal(25); // isCritical = false
var critHeal = new Heal(50, true); // isCritical = true
Example 2: Multiple Optional Parameters¶
using DxMessaging.Core.Attributes;
using UnityEngine;
[DxBroadcastMessage]
[DxAutoConstructor]
public readonly partial struct SpawnEffect
{
[DxOptionalParameter(1.0f)]
public readonly float scale;
[DxOptionalParameter]
public readonly Color color;
[DxOptionalParameter(5.0f)]
public readonly float duration;
[DxOptionalParameter(false)]
public readonly bool looping;
}
// Usage:
var defaultEffect = new SpawnEffect(scale: 1.0f); // Annotated defaults
var largeEffect = new SpawnEffect(2.5f); // Custom scale
var redEffect = new SpawnEffect(1.0f, Color.red); // Custom color
var customEffect = new SpawnEffect(1.5f, Color.blue, 10f, true); // All custom
Example 3: Mix of Required and Optional Fields¶
[DxUntargetedMessage]
[DxAutoConstructor]
public readonly partial struct GameEvent
{
// Required fields (must be provided)
public readonly string eventName;
public readonly int playerId;
// Optional fields (have defaults)
[DxOptionalParameter(0)]
public readonly int score;
[DxOptionalParameter("")]
public readonly string metadata;
}
// Usage:
var minimalEvent = new GameEvent("LevelStart", 1);
var scoredEvent = new GameEvent("EnemyKilled", 1, 100);
var fullEvent = new GameEvent("Achievement", 1, 500, "first_blood");
Example 4: Game Settings Message¶
using DxMessaging.Core.Attributes;
using DxMessaging.Core.Extensions;
[DxUntargetedMessage]
[DxAutoConstructor]
public readonly partial struct AudioSettingsChanged
{
[DxOptionalParameter(1.0f)]
public readonly float masterVolume;
[DxOptionalParameter(0.8f)]
public readonly float musicVolume;
[DxOptionalParameter(1.0f)]
public readonly float sfxVolume;
[DxOptionalParameter(true)]
public readonly bool muteWhenUnfocused;
}
// Apply all defaults
var audioSettings = new AudioSettingsChanged(masterVolume: 1.0f);
audioSettings.Emit();
// Only change music volume
var musicOnly = new AudioSettingsChanged(musicVolume: 0.5f);
musicOnly.Emit();
// Change multiple settings
var multi = new AudioSettingsChanged(0.7f, 0.6f, 0.9f, false);
multi.Emit();
Best Practices¶
Success: Recommendations
- Order matters -- Place required fields before optional fields in your struct
- Use meaningful defaults -- Choose defaults that represent the most common use case
- Prefer explicit values -- Use
[DxOptionalParameter(0)]instead of[DxOptionalParameter]when clarity helps- Use Expression for complex types -- Don't fight the type system; use
Expressionfor enums and Unity types- Document unusual defaults -- If a default isn't obvious, add a comment explaining why
Why Use Attributes Instead of Manual Implementation¶
Attribute Definition (Clean, Automatic)¶
[DxTargetedMessage]
[DxAutoConstructor]
public readonly partial struct Heal
{
public readonly int amount;
}
Resulting public type¶
The handwritten fields and generated members form this type:
using System;
using DxMessaging.Core;
using DxMessaging.Core.Messages;
public readonly partial struct Heal : IMessage, ITargetedMessage
{
public readonly int amount;
public Heal(int amount)
{
this.amount = amount;
}
public Type MessageType => typeof(Heal);
}
Benefits¶
- Less code - 50% fewer lines
- Fewer bugs - Can't forget fields in constructor
- Focused - Focus on data, not boilerplate
- Refactor-safe - Add field? Constructor updates automatically!
Complete Example: Attribute Definition vs Generated Output¶
Attribute Definition (8 lines)¶
using DxMessaging.Core.Attributes;
[DxBroadcastMessage]
[DxAutoConstructor]
public readonly partial struct PlayerDamaged
{
public readonly int amount;
public readonly string damageType;
}
Resulting public type¶
The handwritten fields and generated members form this type:
using System;
using DxMessaging.Core;
using DxMessaging.Core.Messages;
public readonly partial struct PlayerDamaged : IMessage, IBroadcastMessage
{
public readonly int amount;
public readonly string damageType;
public PlayerDamaged(int amount, string damageType)
{
this.amount = amount;
this.damageType = damageType;
}
public Type MessageType => typeof(PlayerDamaged);
}
Result¶
- Same functionality
- Less code to maintain
- Automatically updates when you add/remove fields
- Works for class messages too
- Zero effort once you mark the struct partial
Advanced: Manual Implementation (When Attributes Aren't Enough)¶
If you omit a route attribute, implement the route interface and provide MessageType yourself. You can use [DxAutoConstructor] independently to generate the constructor, or write it by hand.
Generated and Manual Message Interfaces¶
The message attributes generate IMessage, the non-generic route interface, and a concrete MessageType property. The bus and emission helpers use generic methods to pass struct messages by reference. Generated messages do not need a generic route interface for those calls.
For a handwritten message, you can implement IUntargetedMessage<T>, ITargetedMessage<T>, or IBroadcastMessage<T>. Those interfaces provide MessageType through their default implementation.
[DxTargetedMessage]
[DxAutoConstructor]
public readonly partial struct Heal
{
public readonly int amount;
}
Closed generic messages on IL2CPP¶
Use an assembly-level DxAotMessage attribute for each closed generic message that can reach an untyped dispatch API before typed registration or emission. The attribute is available in 4.0.0 and accepts one concrete message Type. See generic messages on IL2CPP for the complete setup and visibility requirements.
"Do I HAVE to use attributes?"¶
Technically no -- but without them you must write the constructor, interface implementation, and MessageType property yourself (for speed, you can optionally leave this off, but it might box on certain call paths). Leaving the attributes on keeps everything consistent for the whole team.
"What if I want custom constructor logic?"¶
Keep the attributes and add a factory/helper so you still benefit from the generated constructor:
[DxUntargetedMessage]
[DxAutoConstructor]
public readonly partial struct ComplexMessage
{
public readonly int value;
public static ComplexMessage FromRaw(int rawValue)
{
int clamped = Math.Clamp(rawValue, 0, 100);
return new ComplexMessage(clamped);
}
}
If you truly must write a custom constructor, drop [DxAutoConstructor] for that type but keep the [DxUntargetedMessage]/[DxTargetedMessage] attribute so the interface plumbing stays consistent.
"Can I mix attribute-based and manual messages?"¶
Yes. Attribute-driven messages happily coexist with string messages and any manual implementations you already have. You can migrate gradually by converting one message at a time:
[DxUntargetedMessage]
[DxAutoConstructor]
public readonly partial struct MessageA
{
public readonly int value;
}
// Existing manual message types keep working alongside attribute-driven ones.
Extension Methods (Emit Helpers)¶
DxMessaging provides extension methods to make emitting messages easy:
using DxMessaging.Core.Extensions; // <- Don't forget this!
using UnityEngine;
// Untargeted (global)
var settings = new VideoSettingsChanged(1920, 1080);
settings.Emit();
// Targeted - GameObject overload
var heal = new Heal(10);
heal.EmitGameObjectTargeted(playerGameObject);
// Targeted - Component overload
heal.EmitComponentTargeted(playerComponent);
// Broadcast - GameObject overload
var dmg = new TookDamage(25);
dmg.EmitGameObjectBroadcast(gameObject);
// Broadcast - Component overload
dmg.EmitComponentBroadcast(this);
// String convenience (for quick prototyping)
"LevelCompleted".Emit();
Located in: DxMessaging.Core.Extensions.MessageExtensions
Automatic overload selection¶
- Extension methods pick the right overload based on type
- Defaults to global
MessageHandler.MessageBus - Pass custom bus with optional parameter
Local Bus Islands (Isolated Testing)¶
Create isolated message buses for tests or subsystems:
using DxMessaging.Core;
using DxMessaging.Core.Extensions;
using DxMessaging.Core.MessageBus;
// Create isolated bus
var testBus = new MessageBus();
var handler = new MessageHandler(new InstanceId(1), testBus) { active = true };
using MessageRegistrationToken token = MessageRegistrationToken.Create(handler, testBus);
// Register on isolated bus
_ = token.RegisterUntargeted<MyMessage>(OnMessage);
token.Enable();
// Emit to isolated bus (won't affect global bus!)
var msg = new MyMessage();
msg.Emit(testBus);
Use cases¶
- Unit tests with explicit registration ownership
- Subsystem isolation (UI has own bus)
- Sandboxing (mod systems, untrusted code)
The token starts disabled. Enable it before emitting, and dispose it at the end of its ownership scope. A local bus isolates routing but still shares runtime settings and pools.
Attributes Quick Reference¶
Message Type Attributes¶
Untargeted¶
Mark as a global message (no target):
Targeted¶
Mark as a message sent to a specific target:
Broadcast¶
Mark as a message broadcast from a source:
Constructor Generation Attributes¶
[DxAutoConstructor]¶
Automatically generates a constructor with all public fields as parameters:
[DxAutoConstructor]
public readonly partial struct Damage
{
public readonly int amount;
public readonly string type;
}
// Generates: Damage(int amount, string type)
[DxOptionalParameter]¶
Makes a constructor parameter optional. Three usage patterns:
Example: Default Value (type default)
Uses the type's default value (
0,false,null, etc.):C#[DxAutoConstructor] public readonly partial struct OptionalFlagMessage { [DxOptionalParameter] public readonly bool flag; } // Generates: bool flag = defaultExample: Custom Value (primitive)
Provides a specific default value:
C#[DxAutoConstructor] public readonly partial struct OptionalCountMessage { [DxOptionalParameter(42)] public readonly int count; } // Generates: int count = 42Example: Expression (complex types)
Resolves constant expressions in the field's declaration scope:
Supported Types¶
These attributes work with:
- Top-level types -- public structs and classes
- Nested types -- types inside other classes
- Internal types -- assembly-private messages
Common Patterns with Attributes¶
Pattern 1: Simple Message (No Data)¶
[DxUntargetedMessage]
public readonly partial struct GamePaused { }
// No constructor needed - empty message
Pattern 2: Message with Data¶
[DxTargetedMessage]
[DxAutoConstructor]
public readonly partial struct Heal
{
public readonly int amount;
}
// Auto-generates: Heal(int amount)
Pattern 3: Message with Optional Fields¶
[DxBroadcastMessage]
[DxAutoConstructor]
public readonly partial struct AttackPerformed
{
public readonly int damage;
[DxOptionalParameter]
public readonly string damageType;
}
// Auto-generates: AttackPerformed(int damage, string damageType = default)
Pattern 4: Complex Message¶
[DxUntargetedMessage]
[DxAutoConstructor]
public readonly partial struct LevelCompleted
{
public readonly int level;
public readonly float time;
public readonly int score;
[DxOptionalParameter]
public readonly bool perfectRun;
[DxOptionalParameter]
public readonly string bonusReason;
}
// All fields become constructor parameters, last two are optional
Pattern 5: Nested Types¶
Define messages inside other classes for better organization:
public partial class GameEvents
{
[DxUntargetedMessage]
[DxAutoConstructor]
public readonly partial struct DifficultyChanged
{
public readonly int difficulty;
}
[DxTargetedMessage]
[DxAutoConstructor]
public readonly partial struct GainExperience
{
public readonly int amount;
}
}
// Usage:
var difficulty = new GameEvents.DifficultyChanged(5);
difficulty.Emit();
Benefits¶
- Organizes related messages into namespaces or classes
- Reduces global namespace pollution
- Works identically to top-level messages
Pattern 6: Internal Types (Assembly-Private Messages)¶
Keep implementation details private to your assembly:
[DxUntargetedMessage]
[DxAutoConstructor]
internal readonly partial struct InternalDebugMessage
{
public readonly string debugInfo;
}
// Only visible within this assembly
// Perfect for internal messaging that shouldn't leak to other packages
Use cases¶
- Implementation details that shouldn't be public API
- Plugin or package-internal messaging
- Test-only messages
FAQ: Source Generators & Attributes¶
"Do I HAVE to use attributes?"¶
No! You can implement interfaces manually:
// Manual (works fine, just more code)
public readonly struct MyMsg : IUntargetedMessage<MyMsg>
{
public Type MessageType => typeof(MyMsg);
}
// Attributes (same result, less code)
[DxUntargetedMessage]
public readonly partial struct MyMsg { }
Recommendation: Use attributes unless you need explicit control.
"Why partial when using attributes?"¶
Source generators need to add code to your type. The partial keyword allows them to extend your struct/class in a separate file.
using System;
using DxMessaging.Core;
using DxMessaging.Core.Attributes;
using DxMessaging.Core.Messages;
// Your file (MyMessage.cs)
[DxUntargetedMessage]
public readonly partial struct MyMessage { }
// Generated file (MyMessage.g.cs - auto-created!)
public readonly partial struct MyMessage : IMessage, IUntargetedMessage
{
public Type MessageType => typeof(MyMessage);
}
Forget partial? You'll get a compile error: "Type must be partial to use source generators"
"Can I see the generated code?"¶
Use your IDE's generated-source view when available. Visual Studio exposes generator output under the project's analyzer dependencies. Navigation to a generated member can also open its generated declaration.
A missing .g.cs file on disk does not prove that generation failed. In .NET SDK projects, writing those files requires EmitCompilerGeneratedFiles. For Unity compilation failures, start with the Console diagnostics below.
"What if I want custom constructor logic?"¶
Keep the attributes and wrap the generated constructor with a helper so you can inject custom logic without losing the source-generated plumbing:
[DxUntargetedMessage]
[DxAutoConstructor]
public readonly partial struct ComplexMessage
{
public readonly int value;
public static ComplexMessage FromRaw(int rawValue)
{
int clamped = Math.Clamp(rawValue, 0, 100);
return new ComplexMessage(clamped);
}
}
If you truly need to hand-craft the constructor, drop [DxAutoConstructor] for that specific type but keep the [DxUntargetedMessage]/[DxTargetedMessage] attribute so the interface implementation is still generated.
"Do attributes affect runtime performance?"¶
No! Source generation happens at compile time. Generated code is identical to hand-written code. Zero runtime overhead.
"Can I mix attributes and manual implementation?"¶
Yes. Attribute-driven messages happily coexist with any legacy manual messages or string messages you already emit. Convert types gradually -- one message at a time:
[DxUntargetedMessage]
[DxAutoConstructor]
public readonly partial struct MessageA
{
public readonly int value;
}
// Existing manual messages keep working alongside attribute-driven ones.
Troubleshooting Source Generators¶
Start with the first compiler error in Unity's Console. Confirm the installed DxMessaging version and use a supported Unity version.
Missing interfaces or MessageType¶
Apply the matching route attribute and mark the message declaration partial. Every containing declaration must also be partial for a nested message. DXMSG003 identifies a non-partial containing type. A handwritten implementation without generator attributes does not need partial unless you split its declaration across files.
Missing constructor¶
[DxAutoConstructor] uses public instance fields in source-file compilation order, then declaration order within each file. Use named arguments for split partial types when you do not control file order. Static fields and properties do not become constructor parameters. A type with no public instance fields gets no generated field constructor.
using DxMessaging.Core.Attributes;
[DxAutoConstructor]
public readonly partial struct WithData
{
public readonly int value;
}
new WithData(42) calls the generated constructor and sets value to 42.
Missing Emit or handler methods¶
Emit helpers are extension methods in DxMessaging.Core.Extensions; import that namespace and implement the matching route contract. The generators do not create emission or handler methods. See the emission troubleshooting steps.
Reporting a compiler failure¶
After fixing the first diagnostic, let Unity finish recompiling. If generation still fails, keep the compiler output and prepare a minimal message declaration, including any containing types. Include the Unity version, DxMessaging version, first diagnostic and declaration in a bug report.
Related Documentation¶
- API Reference -- Complete API documentation
- Message Types -- When to use untargeted, targeted, and broadcast messages
- Quick Reference -- Cheat sheet
- Design & Architecture -- How source generation works internally
Summary¶
Source generators = Code wizards that write boilerplate for you¶
Use attributes for¶
- Clean, maintainable code
- Automatic constructor generation
- Zero boilerplate
- Refactor safety
Use manual implementation for¶
- Custom constructor logic
- Explicit control
- Understanding exactly what happens
Recommendation: Start with attributes (they cover most cases), switch to manual only when needed.