[Godot 4, C#] How to recreate Unitys [RequireComponent(typeof()]?

I want to add child nodes of certain types when I create a new instance of my class.
I haven’t found any notifications or other ways to achieve this.

Basically I want something like this run when I create a new scene instance in editor. But currently it works only when the scene is run.

    public override void _Notification(int what)
    {
        if (what == NotificationSceneInstantiated)
        {
            if (Health == null && GetNodeOrNull<Health>("Health") == null)
            {
                Health = new Health();
                AddChild(Health);
            }
        }
    }

And [Tool] seems not to work for this?
I know I could simply add those nodes manually, but I’m lazy. :grimacing:

1 Like

for [Tool] maybe better use
public override string[] _GetConfigurationWarnings() this should work in editor,
I don’t know what is health but maybe is better make resource instead node??

@trizZzle
if you declare your resource with new() you will have not null resource by default.
while your class is Health : Resource
[export] Health health = new();

resources work better when have [GlobalClass] without you can put any resource in inspector what not really make sense for C#

Do you mean you don’t see healh in the visual tree in the editor? if that’s your problem do something like this:

Health = new Health();
AddChild(Health);
health.Owner = this;<=======have to be assigned after addchild

I believe after'AddChild(Health);
health.Owner == this will be true

after ‘AddChild(Health);’
‘health.Owner == this’ will be false as ‘Owner’ will be null

1 Like

I mean, do you want a warning or you want to automatically create the Node if it doesn’t exist?

Here’s how to create custom warnings for scenes.

Or, in that method (_get_configuration_warnings) you could instantiate the missing node if you find it’s not assigned instead of sending a warning.

2 Likes

verry intresting thank you