godotgdscriptgodot4

Invalid call. Nonexistent function 'instantiate' in base 'GDScript'


When launching the game I get this error. Is there any way to solve the problem?

extends Node2D

var coin = preload("res://coin.gd")

func _on_timer_timeout():
    var coinTemp = coin.instantiate()   
    var generator = RandomNumberGenerator.new()
    var genint = randi_range(50, 500)
    coinTemp.position = Vector2 (genint,560) 
    add_child(coinTemp)

I couldn't find any information on how to solve this problem


Solution

  • You are not preloading a PackedScene, but a gdscript class. From looking at your code I assume you have an actual coin scene you want to add to your current scene. (Since you want to add the instance to your tree)

    So you have to change

    var coin = preload("res://coin.gd")
    

    to the path of your coin scene, not your coin script:

    var coin = preload("res://coin.tscn")