Hi i am a beginner , i wanted to make a 2d shooter that have multiple weapons and difference types of projectile .
What i am trying to do now is instantiate a projectile then set the variables for the projectile using resources after (like in the code).
I feels like this is a very un-optimized way of doing this , because i instantiate a new projectile then set the data every times the player shoot.
Is there any better way to implement this ? Thanks for the help
#I need help with spawning projectile
11 messages · Page 1 of 1 (latest)
Hey! I am a beginner myself so this might not be the best way.
You could try to set up a basic Projectile node tree (as some sort of prefab) and let other inherit these attributes and instanciate them instead.
You can, in your projectile code, do class_name Projectile and then "extends Projectile" instead of extends Node2D, Area2D or whatever.
So basically:
Create a projectile prefab node tree
Copy it
Make it more specific in the code
Inherit (extend) from base projectile class
Instanciate the specific projectile
the problem with your code is that you are instantiating the class of the Projectile it looks like
instantiate() is for PackedScene. So you need to create a PackedScene of you projectile and load it in a variable that you can then instantiate
in case you are not familiar with the concept, PackedScene is when you save your node as a scene.
You can reference by either preloading the path
@onready var projectile_template:PackedScene = preload("res//scenes/projectile_template.tscn") )
or exposing the variable so that you can drag and drop the scene in the inspector
@export var projectile_template:PackedScene
Thanks for the answer ! I will try this
I planned to use inheritance at first but idk if it is efficient to do so because i want to have alot of difference weapons and projectiles .
My bad , i do use an export variable
@export var Projectile : PackedScene
but only capture a short piece of my code .
I
I would avoid the name repetition then. Might cause you problems in the future.
Godot's guidelines advise to use snake_case for variables btw
(and you can remove the "pass" after your code)
Thanks :D i coming from a static typed language (java) so there is some part i am not familiar with , i have both snake_case and camel_case as variables name so definitely need a clean up
and about your actual question, there is nothing wrong with your approach. Worry about optimizing if it starts giving you trouble. The instantiation of the projectile is probably the slowest part (unless you have an enormous amount of data to set to it) which can be improved with pooling.