How would you instantiate enemies and set their HP through code?

Godot Version

Godot 4.2


Let’s say I have a central game scene which will place various entities around the map, and each enemy has its own HP , which is not decided by the enemy itself, but the game scene, and said HP variable is inherited by a base class.
I think the correct call here would be define each enemy as a scene, but doing so, when instantiating a PackedScene, it returns the node, not the scene, so something like

Enemy = enemyPackedScene.instantiate.()
Enemy.HP = 10

doesn’t actually work, so I’m not sure if the scene route is the best one here.
How would you instantiate these enemies? Is having them as scenes is the best way to do it? Saving these enemies as scripts and composing the scenes through an _init() function would also solve this issue but is it the suggested way here?

The code you posted should work, that’s pretty much how you do it. Have you tested it?
The node returned by instantiate() is the scene (the root node of the scene).

Then this is all my bad, I guess the issue, surprisingly, comes with inheritance.

The script for the enemy doesn’t have the HP var, the HP var is inherited by a base class I’ve called Entity.

The script of the Enemy extends the Entity, so it does have an HP variable, it’s just that I can’t set it as I mentioned before.

It should still work, Enemy.HP is how you can access variables, even if they’re inherited from a base class.

Sometimes when I add / change something in a base class Godot doesn’t see the change and the editor shows an error until I reload the project.

Welp, reloading didn’t work so something was clearly wrong. I reinstalled godot, opened a new project, copy-and-pasted everything and it’s working fine now. I guess this was more of a bug, but the node wasn’t extending properly.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.