Correct pattern for initializing components in Unity?
Posted: 28 Aug 2025, 18:10
I sometimes foot-gun myself with component initialization in the code-behind constructor on Unity. I'm curious if there's a better pattern documented that I missed.
Let's say I have a control that does this:
Because controls get constructed in the editor even when Preview Enabled is false, the rest of this code will run. LoadAtlas and UpdateSprites try to access various Addressables that aren't available when the game isn't loaded, creating all sorts of static havoc internal to Noesis. I've had it completely hose my system until I reboot. The problem is likely due to Noesis trying to bind some incorrectly setup texture - but it isn't super important because it shouldn't ever happen. It just isn't code I want to run when not in the game.
I have the UNITY_EDITOR define there to short circuit the init process, which fixes things. The foot-gun is if I write code that Noesis tries to run in the editor and I forget to add a define like this.
Is there a better component initialization pattern I can adopt?
Let's say I have a control that does this:
Code: Select all
public MaskedSprite()
{
InitializeComponent();
}
private void InitializeComponent()
{
NoesisUnity.LoadComponent(this, "MaskedSprite");
#if UNITY_EDITOR
if (!EditorApplication.isPlaying)
return;
#endif
_spriteRect = FindName("SpriteRect") as Rectangle;
_imageBrush = FindName("SpriteBrush") as ImageBrush;
_maskShader = FindName("MaskShader") as MaskedSpriteBrush;
LoadAtlas();
UpdateSprites();
}
I have the UNITY_EDITOR define there to short circuit the init process, which fixes things. The foot-gun is if I write code that Noesis tries to run in the editor and I forget to add a define like this.
Is there a better component initialization pattern I can adopt?