Should we still check if player exists?

func new_game():
	player = player_scene.instantiate()
	player.global_position = player_spawn_position
	add_child(player)
	
	camera = camera_scene.instantiate()
	camera.setup_camera(player)
	add_child(camera)

	if player:
		level_generator.setup_level_generator(player)

Here we instantiated the Player scene in gdscript, a few lines later we check if player exists and then call the setup_level_generator(player) function.

If we remove the if statement, is there a way that the player will be null?

I don’t think so, as long as the reference to the player scene doesn’t break and the player scene itself has nodes. Either way, a broken reference will break the code before reaching this point, and I don’t think a nodeless scene can even be saved as a file, though I suppose you could try to make one in code. Maybe if the player was being deserialized from a .json file or something, since loading a corrupted file could result in just about anything.

Actually, now that I think about it, this is probably habit-building for exactly that situation.

The only reason I can think of to check if the player exists here, in this project, is so that you could write your own meaningful exception handling behaviour in the event that the cows freeze over and player somehow does become null. If you’re following with the lectures though, I’m pretty sure you can do without it unless you’ll be using the else for something.

1 Like

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

Privacy & Terms