Trouble understanding Type Casting

Godot Version

4.2.1

Question

I’m working through a tutorial series (https://www.youtube.com/playlist?list=PL6SABXRSlpH8CD71L7zye311cp9R4JazJ) and the author uses type casting in his code a lot. For example:

func _ready() -> void:
	for child in get_children():
		var card_ui := child as CardUI
		card_ui.reparent_requested.connect(_on_card_ui_reparent_requested)

I hadn’t come across the x as y so I looked it up in the docs to discover casting.

My question is, why would you do this as opposed to doing something like:

func _ready() -> void:
	for child in get_children():
		if child is CardUI:
		child.reparent_requested.connect(_on_card_ui_reparent_requested)

The top example is casting the child as a CardUI so the engine knows its a CardUI and will also help provide the auto-complete functions when scripting, etc.

The bottom example is just doing a type check. So you aren’t actually type casting, but just doing a check on its type. So if the child is of type CardUI then continue running whatever is in the if block.

1 Like

Oh I see. So the editor can help me with the functions if I tell it to expect it to be type CardUI. What happens if one of the children (say I added a Sprite2D later for some flair or something). Will this crash my game since I’m not first checking if the child is a CardUI before type casting it?

EDIT: I don’t know why I asked when I could just try it.

It does crash if I did that so I assume the best way to hand this would be to check the type before casting it correct?

1 Like

In C# you get back a null if you cast to an invalid type. I guess it is same in gdscript? So if you know it can be more than one type just check for nulls too, or do the is check. In C# you can cast with is, which is quite nice since you use it in an if statement and will thus not encounter the null exception if (child is CarUI cui) cui.DoSomething();

1 Like

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