+2 votes

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!

in Engine by (25 points)

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

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

2 Answers

+3 votes

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.

by (27,593 points)
0 votes

if the bullet is a scene:

export var bullet: PackedScene

var created_bullet = bullet.instance()

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

created_bullet = Bullet.new()
by (207 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.