Create instance of custom class

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Marteon27
:warning: Old Version Published before Godot 3 was released.

Hello!
I have a bullet which has var damage in its _init(damage) I set the damage. How can I instanciate this object and attach it to my bullet node?
Thanks for your help!

What is bullet? a class that you defined with the class keyword?

Zylann | 2017-06-30 10:38

Actually my script is called bullet.gd so my class in not an inner class.

Marteon27 | 2017-06-30 12:49

:bust_in_silhouette: Reply From: Zylann

In order to be able to attach a script to a node, it must at least inherit from Node. Otherwise I’m not sure if it’s supposed to work.
If your script doesn’t have any extends, then it won’t be a node.

Such a script can be instanced by doing this though:

var obj = preload("bullet.gd").new()`

Or this:

const Bullet = preload("bullet.gd")

func _ready():
    var obj = Bullet.new()

But this won’t create a node instance or attach to a node, it will just be a custom object with variables and functions, that only lives in code.

Also, in addition to inheritance, I’m not sure if _init is called on Node scripts, usually we have _ready or field initializers.

:bust_in_silhouette: Reply From: luislodosm

if the bullet is a scene:

export var bullet: PackedScene

var created_bullet = bullet.instance()
get_tree().get_root().add_child(created_bullet)

If the bullet is a custom class script (bullet.gd with class_name = Bullet):

created_bullet = Bullet.new()