The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates.

godotengine.org | Twitter

0 votes

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? (https://docs.godotengine.org/en/3.1/getting_started/scripting/c_sharp/c_sharp_differences.html#export-keyword) I haven't been able to see any mention of this anywhere.

Something like this maybe?

public class Game : Node
{
    [OnReady]
    public Sprite sprite = GetNode("Sprite");
}
in Engine by (1,663 points)

1 Answer

0 votes

just do it in the _Ready() function?

public Sprite sprite;
public override void _Ready()
{
    sprite = GetNode<Sprite>("Sprite");
}
by (220 points)

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

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.

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

There's a recent proposal to add a C# version of onready to Godot proper: https://github.com/godotengine/godot-proposals/issues/2425

In the meantime, I wrote an open-source C# Source Generator that can generate the boilerplate, to make it more terse: https://github.com/31/GodotOnReady

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.