# Published state fields are now automatically initialized, no need in most cases for DesignedComponent calls

**URL:** https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664
**Category:** News
**Created:** [October 16, 2022, 12:25am UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664 "2022-10-16T00:25:58Z")
**Posts on this page:** 14
**Page:** 1

<div class="post-metadata">

### Author: ![michalis](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/michalis/32/3_2.png) [@michalis](https://forum.castle-engine.io/u/michalis)
#### Post date: [October 16, 2022, 12:25am UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/1 "2022-10-16T00:25:58Z")

</div>

| [![Van Gogh , Bedroom in Arles , night - by ruslans3d from https://sketchfab.com/3d-models/van-gogh-bedroom-in-arles-night-7c28126099404406bd0f5c150d809394](https://forum.castle-engine.io/uploads/default/original/1X/fbb59e9d25dd3b6e8622e267bf2a887b47e17554.png)](https://i0.wp.com/castle-engine.io/wp/wp-content/uploads/2022/10/Zrzut-ekranu-z-2022-10-16-02-19-49.png?ssl=1 "Van Gogh , Bedroom in Arles , night - by ruslans3d from https://sketchfab.com/3d-models/van-gogh-bedroom-in-arles-night-7c28126099404406bd0f5c150d809394") |

This is another important _“quality of life”_ improvement for developers:

You no longer need to explicitly initialize the components you want to access using `DesignedComponent` method. You just need to move your fields to the `published` section to make them initialized automatically.

## Detailed explanation of the difference

All (or most) of the calls like below can be now removed:

```
LabelFps := DesignedComponent('LabelFps') as TCastleLabel;
```

Previously, we advised to organize your state like this:

```
type
  TStateMain = class(TUIState)
  private
    { Components designed using CGE editor, loaded from gamestatemain.castle-user-interface. }
    LabelFps: TCastleLabel;
  public
    constructor Create(AOwner: TComponent); override;
    procedure Start; override;
  end;

constructor TStateMain.Create(AOwner: TComponent);  
begin  
inherited;  
DesignUrl := ‘castle-data:/gamestatemain.castle-user-interface’;  
end;

procedure TStateMain.Start;  
begin  
inherited;  
{ Find components, by name, that we need to access from code }  
LabelFps := DesignedComponent(‘LabelFps’) as TCastleLabel;  
end;
```

Now, we advise a simpler approach:

```
type
  TStateMain = class(TUIState)
  published
    { Components designed using CGE editor.
      These fields will be automatically initialized at Start. }
    LabelFps: TCastleLabel;
  public
    constructor Create(AOwner: TComponent); override;
  end;

constructor TStateMain.Create(AOwner: TComponent);  
begin  
inherited;  
DesignUrl := ‘castle-data:/gamestatemain.castle-user-interface’;  
end;
```

Of course you may still find it useful to define `Start` method, to initialize various things about your state. But there’s no need for it if it was only doing `DesignedComponent` calls.

## What’s going on under the hood

The published fields of the `TUIState` descendants are now automatically initialized when the design is loaded. Right before `Start`, the published fields (that have names matching some object in the design) are now automatically set to the corresponding objects. At `Stop` (when design is unloaded) these fields are set to nil.

As a bonus (advantage over previous solution) this avoids having dangling references after `Stop`. While previously you could set all your references to `nil` manually in `Stop` method… likely nobody did it, as it was a tiresome and usually pointless job. Now they are `nil` after Stop automatically, so accessing them will result in clearer errors (and can be safeguarded by `X <> nil` reliably).

I should also mention one disadvantage from the previous approach: if you make a typo in component name, e.g. declare `BabelFps` instead of `LabelFps`, then the mistakenly-named field will just remain uninitialized. Nothing will make an automatic exception like _“BabelFps not initialized!”_. Of course any code doing `BabelFps.Caption := 'aaa';` will crash and the debugger should clearly show that `BabelFps` is `nil`. And you can write something like `Assert(BabelFps <> nil);` in `Start` to get explicit exception in case of mistake.

This is very consistent with how Delphi VCL and Lazarus LCL initialize their form fields.

## Our conventions — where to put the published section?

I admit I had a little discussion with myself about _“where to put the `published` section”_?

Following our usual conventions for writing components, the `published` section should go as last. We usually write `private`, then `public`, then `published`. So I wanted to have section in the increasing order of “being exposed”:

```
type
  TStateMain = class(TUIState)
  // MOST INTERNAL
  private
    MyInternalStuff: Integer;
  // EXPOSED TO OUTSIDE WORLD
  public
    constructor Create(AOwner: TComponent); override;
  // EXPOSED TO OUTSIDE WORLD ALSO THROUGH RTTI
  published
    { Components designed using CGE editor.
      These fields will be automatically initialized at Start. }
    LabelFps: TCastleLabel;
  end;
```

But eventually I came to the conclusion that it is a bit unnatural in this case. Basically, Delphi VCL and Lazarus LCL are right to put it at the beginning. Because in the usual case, you don’t think about this published section as _“the most exposed identifiers for outside code”_. You think about it as _“internal components I need to access to implement my design”_.

And it’s kind of an _“unfortunate but sensible limitation”_ that it means that these things have to be also exposed to everything from the outside. This fact makes sense if you realize that the automatic initialization requires RTTI (_RunTime Type Information_, known also as [reflection](https://en.wikipedia.org/wiki/Reflective_programming) in various other languages). Things that RTTI has access to are naturally available to the outside world, through RTTI. So it would not be consistent for compiler to “hide” the fields in the `published` section while still making these identifiers available through RTTI.

Yet, when creating Delphi VCL form, or Lazarus LCL form, or CGE state, you usually don’t really want to “expose” these fields to the outside world. You want to access them right within your form / state. Thus, having them at the beginning of the state makes sense. And is consistent with Delphi VCL / Lazarus LCL as a bonus.

Still I decided to explicitly spell the `published` section name everywhere. This allows me to easily say in documentation _“put your field in the `published` section”_. I don’t need to say “initial section” or “automatic section” and users don’t need to understand how it works and how `{$M+}` in Pascal works and whether `TUIState` was compiled with `{$M+}`. So, in the end, I propose to write:

```
type
  TStateMain = class(TUIState)
  published
    { Components designed using CGE editor.
      These fields will be automatically initialized at Start. }
    LabelFps: TCastleLabel;
  private
    MyInternalStuff: Integer;
  public
    constructor Create(AOwner: TComponent); override;
  end;
```

Have fun with this! I have already updated our templates, our [manual like here](https://castle-engine.io/manual_state_events.php), and some (but not all!) examples to follow the new convention.

---

<div class="post-metadata">

### Author: ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)
#### Post date: [October 16, 2022, 1:28pm UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/2 "2022-10-16T13:28:04Z")

</div>

I gave it a first try by outcommenting the first TCastleImageTransform in TStatePlay.Start but got errors because the transform cannot be found?

![Clipboard01](https://forum.castle-engine.io/uploads/default/original/1X/606d1ce8627c6b357911d9751c9e5cd9acaf345c.png)

```auto
procedure TStatePlay.Start;
begin
  inherited;

// WestBeachTransform := DesignedComponent('WestbeachTransform') as TCastleImageTransform;
  PassagebeachTransform := DesignedComponent('PassagebeachTransform') as TCastleImageTransform;
  EastbeachTransform := DesignedComponent('EastbeachTransform') as TCastleImageTransform;  

```

Relevant TStatePlay is:

```auto
type
    TStatePlay = class(TUIState)

    private
    PlayerMouse: TGamemouse;
    Player: TAvatar;
    Location: TLocation;
    PlayingSound1, PlayingSound2: TCastlePlayingSound;

   PlayerTransform: TCastleTransform;

 
  published
      Label1, Label2, Label3, Label4, NarratorLabel, NPCTalkLabel: TCastleLabel;

      procedure CreatePlayerMouse;
      procedure CreateProps;
      procedure CreateLocation;
      procedure CreatePlayer;
      procedure CreateNPC;

         procedure Westbeach;
      procedure Passagebeach;
      procedure Eastbeach;

 public
      procedure Stop; override;
      constructor Create(AOwner: TComponent); override;
      procedure Start; override;
      procedure Update(const SecondsPassed: Single; var HandleInput: Boolean); override;
      function Press(const Event: TInputPressRelease): Boolean; override;          
 end;

```

```auto
constructor TStatePlay.Create(AOwner: TComponent);
begin

  inherited;

  DesignUrl := 'castle-data:/gamestateplay.castle-user-interface';
end;      

```

---

<div class="post-metadata">

### Author: ![michalis](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/michalis/32/3_2.png) [@michalis](https://forum.castle-engine.io/u/michalis)
#### Post date: [October 16, 2022, 4:11pm UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/3 "2022-10-16T16:11:54Z")

</div>

@Carring In the `published` section you show I don’t see a declaration of `WestBeachTransform`.

See the post description – only the fields in the `published` section are initialized. If you remove the line

```auto
WestBeachTransform := DesignedComponent('WestbeachTransform') as TCastleImageTransform;

```

then you need to make sure the field `WestBeachTransform` is in `published` section.

---

<div class="post-metadata">

### Author: ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)
#### Post date: [October 16, 2022, 4:51pm UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/4 "2022-10-16T16:51:59Z")

</div>

> [@michalis](#):
>
> then you need to make sure the field `WestBeachTransform` is in `published` section

I still get the error?

 ![Clipboard01](https://forum.castle-engine.io/uploads/default/original/1X/7d36bfb0359eec82319ed6ed9481e4785e866baa.png)

---

<div class="post-metadata">

### Author: ![michalis](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/michalis/32/3_2.png) [@michalis](https://forum.castle-engine.io/u/michalis)
#### Post date: [October 16, 2022, 5:12pm UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/5 "2022-10-16T17:12:56Z")

</div>

> [@Carring](#):
>
> I still get the error?

Maybe it’s some unrelated issue? What you show looks good.

`WestbeachTransform` will be initialized, if your design (`castle-data:/gamestateplay.castle-user-interface`) will contain a component with the same name.

You can verify it by doing things like

```delphi
Assert(WestbeachTransform <> nil);
WritelnLog('Got WestbeachTransform ' + WestbeachTransform.Name);

```

in Start method.

If you cannot solve it, then maybe you have some unrelated problem. As usual, please submit a full testcase to reproduce the problem.

---

<div class="post-metadata">

### Author: ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)
#### Post date: [October 17, 2022, 9:16am UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/6 "2022-10-17T09:16:44Z")

</div>

Now the WritelnLog identifier cannot be found. 🤔  
Though ‘Classes’ is in my uses list.

 ![Clipboard01](https://forum.castle-engine.io/uploads/default/original/2X/c/cc2d0637f65804193a9750ac3a4a2dbf937a2579.png)

---

<div class="post-metadata">

### Author: ![eugeneloza](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/eugeneloza/32/12_2.png) [@eugeneloza](https://forum.castle-engine.io/u/eugeneloza)
#### Post date: [October 17, 2022, 9:43am UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/7 "2022-10-17T09:43:16Z")

</div>

`WriteLnLog` is in `CastleLog` unit.

---

<div class="post-metadata">

### Author: ![michalis](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/michalis/32/3_2.png) [@michalis](https://forum.castle-engine.io/u/michalis)
#### Post date: [October 17, 2022, 11:00am UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/8 "2022-10-17T11:00:08Z")

</div>

> [@Carring](#):
>
> Now the WritelnLog identifier cannot be found

You really can find such things yourself 🙂 Go to API docs, [Castle Game Engine: API Reference](https://castle-engine.io/apidoc/html/) , and type WritelnLog in the search box: [Search Results](https://castle-engine.io/apidoc/html/tipue_results.html?q=WritelnLog) .

---

<div class="post-metadata">

### Author: ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)
#### Post date: [October 17, 2022, 11:54am UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/9 "2022-10-17T11:54:52Z")

</div>

Yes, I did that before my question 🙂 but could not find the unit in search results.  
Okay, so its in CastleLog unit (thanks Eugeneloza).  
But now I almost don’t dare to ask where I can find the output of it?  
🙊

---

<div class="post-metadata">

### Author: ![eugeneloza](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/eugeneloza/32/12_2.png) [@eugeneloza](https://forum.castle-engine.io/u/eugeneloza)
#### Post date: [October 17, 2022, 12:21pm UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/10 "2022-10-17T12:21:47Z")

</div>

![2022-10-17 15_20_12-Greenshot](https://forum.castle-engine.io/uploads/default/original/2X/0/0cf7d823e269d25028902968e65b58c6fc58830d.png)

it’s in system drive → Users → UserName → /AppData/Local → your-project-name

---

<div class="post-metadata">

### Author: ![eugeneloza](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/eugeneloza/32/12_2.png) [@eugeneloza](https://forum.castle-engine.io/u/eugeneloza)
#### Post date: [October 17, 2022, 12:25pm UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/11 "2022-10-17T12:25:00Z")

</div>

Sometimes it’s more useful to have it more interactive: then comment-out `{$apptype GUI}` and you’ll have a good real-time window with your logs.

 ![2022-10-17 15_22_12-Greenshot](https://forum.castle-engine.io/uploads/default/original/2X/0/085367b969a688413d525192ca7b6d796131d77d.png)

On Linux you always get it, just go to View → Debug Window → Console (Shift+Alt+O or Shift+Ctrl+O if I remember correctly).

---

<div class="post-metadata">

### Author: ![michalis](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/michalis/32/3_2.png) [@michalis](https://forum.castle-engine.io/u/michalis)
#### Post date: [October 18, 2022, 9:32am UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/12 "2022-10-18T09:32:50Z")

</div>

See also manual [Logging | Manual | Castle Game Engine](https://castle-engine.io/log) that shows how to use log and where is it displayed.

---

<div class="post-metadata">

### Author: ![Carring](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/carring/32/1950_2.png) [@Carring](https://forum.castle-engine.io/u/Carring)
#### Post date: [October 18, 2022, 10:01am UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/13 "2022-10-18T10:01:39Z")

</div>

@michalis Thanks. It is documented well. Though it would be great if there was a search field in the online manual so any keywords can be found easily.  
🙂

---

<div class="post-metadata">

### Author: ![michalis](https://forum.castle-engine.io/user_avatar/forum.castle-engine.io/michalis/32/3_2.png) [@michalis](https://forum.castle-engine.io/u/michalis)
#### Post date: [October 18, 2022, 12:32pm UTC](https://forum.castle-engine.io/t/published-state-fields-are-now-automatically-initialized-no-need-in-most-cases-for-designedcomponent-calls/664/14 "2022-10-18T12:32:01Z")

</div>

> [@Carring](#):
>
> Though it would be great if there was a search field in the online manual so any keywords can be found easily.

Indeed. For now you can e.g. use queries with `site:castle-engine.io`, this works in at least [https://duckduckgo.com/](https://duckduckgo.com/) and Google. Like to find “log”, search “site:castle-engine.io log”.

 ![screenshot 2022-10-18 14:32:58 select](https://forum.castle-engine.io/uploads/default/original/2X/a/affd68d8dce5dbf5c929573c2ea4117ef9c59b20.png)
