Can't get scene to instance and get added as a child

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

Hi Godot masters! I am rather new to gamedev but very enthusiastic. Ran into a little snag trying to instance and add_child. I am getting the error: Invalid type in function ‘add_child’ in base ‘Node2D (Parallax_Example.gd)’. Cannot convert argument 1 from Object to Object.

extends Node2D
var new_house = preload("res://BuildingWalls.tscn")
func _ready():
	new_house.instance()
	add_child(new_house)

I am sure its because I forgot something, just can’t think of what it is. The BuildingWalls.tscn is added as a singleton and autoload is checked. BuildingWalls is a scene with a Node2d base with a sprite, polygon2d, skeleton2d & bone2d children. It works if I instance the scene in the editor before runtime.
Thanks to anyone that can point me in the right direction.

:bust_in_silhouette: Reply From: kidscancode

The new_house variable is the loaded PackedScene, and then you do add_child(new_house). This is the source of the error.

Your problem is that you’re calling instance() to create the scene’s nodes but not assigning the result anywhere.

extends Node2D
var new_house = preload("res://BuildingWalls.tscn")
func _ready():
    var house_instance = new_house.instance()
    add_child(house_instance)

Thanks! That fixed it.

Accoucheur | 2019-09-04 14:28