C# onready support?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Eric Ellingson

Is there a way to define a class property with some sort of “onready” functionality, similar to how it’s done in gdscript? Could it be something similar to how exports are defined? (API differences to GDScript — Godot Engine (3.1) documentation in English) I haven’t been able to see any mention of this anywhere.

Something like this maybe?

public class Game : Node
    public Sprite sprite = GetNode("Sprite");
:bust_in_silhouette: Reply From: Jason Swearingen

just do it in the _Ready() function?

public Sprite sprite;
public override void _Ready()
	sprite = GetNode<Sprite>("Sprite");

Thanks for the response. I’m aware of that approach, but was hoping there was something a little more terse available.

Eric Ellingson | 2020-01-08 23:04

They could build a Attribute system to do what you want,

The problem is it’s a lot of work, and pretty bad performance, and (arguably) makes your code harder to read. So very much not surprised this isn’t supported.

Jason Swearingen | 2020-01-09 14:46

thanks I came here looking for onready var timer: Timer = $Timer alternative in C#.

steelx | 2021-02-25 18:01

There’s a recent proposal to add a C# version of onready to Godot proper: Add OnReady annotation to C# · Issue #2425 · godotengine/godot-proposals · GitHub

In the meantime, I wrote an open-source C# Source Generator that can generate the boilerplate, to make it more terse: GitHub - 31/GodotOnReady: A C# Source Generator that adds convenient onready-like features to your C# scripts in Godot Mono (3.x) without any reflection.

It generates _Ready() based on [OnReadyGet("Sprite")] private Sprite _sprite;. (It also optionally exports a NodePath property so you can change "Sprite" for specific nodes in the editor.) It doesn’t use reflection, so it doesn’t have that performance cost.

31 | 2021-03-20 18:35