A few questions about C# codes in Your first 2D game tutorial

Your Godot version:
v4.2.2.mono
Issue description:
In this part of the tutorial, the following code is given:

async public void ShowGameOver()

I wanted to see if there is a specific reason that the code is written as above? It works correctly if you write the code as follows:

public async Task ShowGameOver()

The second question is, isn’t it better to take the code that needs to be called a lot in the constructor or the _ready method once and use it several times? For example, this GetNode<Label>("Message") code is used a lot in this section, can it be used as follows?

private Label _labelMessage;
public HUD()
{

	_labelMessage = GetNode<Label>("Message");
}
public void ShowMessage(string text)
{
	var message = _labelMessage;
	message.Text = text;
	message.Show();

	GetNode<Timer>("MessageTimer").Start();
}

public async Task ShowGameOver()
{
	ShowMessage("Game Over");

	var messageTimer = GetNode<Timer>("MessageTimer");
	await ToSignal(messageTimer, Timer.SignalName.Timeout);

	var message = _labelMessage;
	message.Text = "Dodge the Creeps!";
	message.Show();

	await ToSignal(GetTree().CreateTimer(1.0), SceneTreeTimer.SignalName.Timeout);
	GetNode<Button>("StartButton").Show();
}

Is calling the code every time to simplify training or is there a special reason?

If you are only talking about the keyword’s order: yes, this is the exact same thing. We should probably edit this, and use the second to be more consistent across documentation pages. If you are talking about the use of async void, I believe that’s something we decided to not touch upon in the documentation. It can be quite intricate, and there are already plenty of resources about it out there.

This GetNode<Label>("Message") call would not work in the constructor, as the node is not in the tree yet. As you are saying, though, it would be fine in _Ready().

The reason this is written like that, as you guessed, is to simplify the doc. This page is simply about showing the reader how to make the HUD work. And trying to teach every potential good practice on top of it would (IMHO) be a disservice. There’s always a delicate balance between what is useful in context to what’s being taught, and what isn’t.

In addition, GetNode<T>(string) is really not that expensive of an operation. It is not performing any complicated lookup, or iterating on the tree extensively. So while there is really no downside in caching its result, the cost of not doing so is far from massive.

1 Like

Comprehensive and complete answer. Thank you very much.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.