Topic was automatically imported from the old Question2Answer platform.
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?
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()
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.