imported variable from autoload is nil

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By kakucho

I’d like to import a variable and a function from autoload, but it says
“invalid type in function ‘gem_found’ in base 'Node2D (Global.gd);. Cannot convert argument 1 from Nil to int.” Why is current_score Nil?

#Global.gd

extends Node2D

#autoload

var current_score = 0

func gem_found(score:int):
	score += 1
	return score 

#Gem.gd

extends Area2D

var Ship = load("res://scene/Ship.tscn")
var Global = preload("res://singletons/Global.tscn")
var global = Global.instance()

var current_score = global.current_score
																																																																																																																																																																																				  
func _on_Gem_body_entered(Ship):
	var current_score =  global.gem_found(current_score)
	print(current_score)
	self.queue_free() 
:bust_in_silhouette: Reply From: AlexTheRegent

if your Global.gd is singleton and enabled in AutoLoad tab (Singletons (Autoload) — Godot Engine (stable) documentation in English), then you don’t have to preload it’s script and instance it. It is automatically available in all scripts via it’s registered name (which is script name by default, in your particular case it would be Global). So you have to change your gem.gd script to

extends Area2D

var Ship = load("res://scene/Ship.tscn")
# var Global = preload("res://singletons/Global.tscn") # <- remove this line
# var global = Global.instance() <- remove this line

var current_score = Global.current_score # <- Access singleton here via it's name, i.e. Global

func _on_Gem_body_entered(Ship):
    var current_score =  Global.gem_found(current_score) # <- Access singleton here via it's name, i.e. Global
    print(current_score)
    self.queue_free()

Note that all autoloaded singletons are automatically added to the “/root” node during game startup.

I got how to use autoload properly, thanks! I also had to set the argument as body, not Ship.

var score = Global.current_score
func _on_Gem_body_entered(body):
	if body.name == "Ship":
		score += 1
		#Global.gem_found(score) keeps returning 1 however many times I hit the gem.
		print(score)
		#as It counts the score of each gem, I should adjust the position of gem instead of removing the child and adding it again.

kakucho | 2022-11-10 00:08