How can I instance by code?

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

Greetings. I’m a newbie in Godot, and I only programmed used structured programming (instead of OOP) before, so it’s been hard to assimilate some Godot concepts.

Well, I’m now programming a quick Asteroids like prototype. I have three scenes for it:

  • A Main scene.
  • A Ship scene.
  • A SmokeParticle scene (I programmed it as a smoke sprite growing and getting more transparent, that I’ll use for smoke particles emitted by the ship).

So, first I programmed the Ship scene and its movement, then I programmed the Main scene, that includes the Ship and a Camera node that follows the ship, and now I want to include the Ship scene code to add instances of the Smoke scene. Problem is that Godot cannot recognize add_child(SmokeParticle) (Parse error: identifier not found: SmokeParticle). What should I do so it could recognize a node from an external scene in my code?

Thanks in advance!

:bust_in_silhouette: Reply From: MysteryGM

Hi, you need to load the scene as a resource first.

#Load the resourse using preload
const MySmokeResource = preload("res://SmokeScene.tscn")

func _ready():
	#Make instance
	var GrabedInstance= MySmokeResource.instance()
	#You could now make changes to the new instance if you wanted
	CurrentEntry.name = "SmokeA"
	#Attach it to the tree
	self.add_child(GrabedInstance)

The development branch documents has an updated resource entry: Resources — Godot Engine (latest) documentation in English
This explains resources better than the old documents.

Thanks, it worked! :slight_smile:

Leandro | 2018-11-22 12:37

What is CurrentEntry in your example? Should that be GrabbedInstance?

rikkiprince | 2021-02-02 18:41

No idea, I (like so many other developers) abandoned Godot a long time ago.

I think you are correct because that is how I used it here: Reddit - Dive into anything
That is what Google tells me.

Man, I had so much hope for this engine back then.

MysteryGM | 2021-02-03 10:29

Why have you bounced off it @MysteryGM? I’ve been using it for a game jam this past week or so, and while it hasn’t kept up with some of the progressions in Unity, it still has good aspects. I would have liked some of the pointier edges to have been fixed in the 2 years since I used Godot last though!

rikkiprince | 2021-02-08 06:40