Inferred as keyword variable VS. typed variable

What’s the difference between:

@export var object_path
@onready var object := preload(object_path).instantiate() as Object

and:

@export var object_path
@onready var object:Object = preload(object_path).instantiate()

The former will return null if the value is not an Object, which should happen since instantiate is a function not being called, as it’s missing it’s parenthesis

The latter should :tm: produce an error at run-time when the value is not an Object, though null values are allowed (like in the first case) a function typed value is not.

extends Node2D # NOT AN AREA2D

func _ready() -> void:
	var t1: Area2D = $"." as Area2D
	print(t1) # prints <null> because `as` casts to null
	var t2: Area2D = $"." # no `as` triggers a error and stack trace
	print(t2)

In your case the second option, without as is probably more helpful as you will get errors quicker rather than stray null values to be set off later on.

1 Like

Thanks, that’s actually insightful.
But I forgot to add the parentheses, which I edited in now.
Would the same ideas apply to them as well?

Yes same ideas, though the Object type is the most base class so everything outside of mathematic base types like int, float, Callables, and Vectors will convert. None of which are stored inside a instantiateable scene.

If you are giving it the requested type both statements will act the same in success, it’s how they differ in failure that’s important. Missing the parenthesis might have actually helped exibit how this behaviour is helpful, you had an error it could catch. Functions like instantiate could be kept in a Callable type variable, it’s a value like anything else.

@onready var object_factory: Callable = preload(object_path).instantiate

func _on_button_pressed() -> void:
    var new_object: Object = object_factory()

I’m confusing myself right now :skull:
When I used an object as a class, it was more like a stand in for other classes in my project.

But, thanks I believe I can apply what you said to anything, with the key point being the latter is safer and throws a error compared to the former returning null. :+1:

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