Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Fyrol |
I’m trying to grab the players HP, then whenever the enemy collides with the player’s HitBox (an Area2D node) it’ll grab the players current HP value. However no matter what I do, I can’t get the script to locate the player. I’ve thought about using get_node() to get the exact path to it, however whenever I would switch scenes, wouldn’t the path get messed up?
The only other solution I could find was something called a simpleton, but I don’t really know how to set one up, and anywhere I’ve found talking about them has told me that I should avoid them at all costs.
extends StaticBody2D
var att = 1
func dealDamage(att):
$Player.currHP - att
func _on_HurtBox_area_entered(area):
dealDamage(att)
func _on_HurtBox_area_entered(area):
//dealDamage(att)
if area.name == "Player":
area.function_name_in_player() //
ramazan | 2022-03-22 10:05
To do a singleton, make a new script and call it Global or something. Then in the project settings, have it loaded in the Autoload option along with a “Main” Node. You declare variables in this script. Then you call this variable anytime in your project’s script with Global.YourVarName. So in this case, Global.HitPoints. Or you can make a variable on the player object as well that takes this value and makes it the current total. So var playercurrentHP = Global.HitPoints. That doesn’t change the global value but allows you to reference it anytime. So a healing spell could be a function like playercurrentHP = hitPoints.
Just be careful with singletons - they can actually make code more coupled and therefore harder to work on. But by referencing that value in the player script, you always have access to it and can store its temporary value as a separate variable as above.
SnapCracklins | 2022-03-23 01:13
Thank you very much
Fyrol | 2022-03-23 02:20