Best practices for component variable's values?

4.3

I’m currently following Bitlytic’s components tutorial to separate my objects into components, however i’m having trouble understanding how to assign values to the variables per object, in the tutorial he assigns the health value in the component’s script, yet this assigns the same value to every object with the component, to accomodate for that he modifies the value from the inspector, but that means he would have to change it for every object in the scene which would not work with dynamic instantiation, therefore i was wondering what is the best practice to accomodate for a case like this.

My first instinct is to assign the values within the object’s script and have the components retrieve it but this could cause some issues (the value is in the object script and components are supposed to unclutter the main object script, using get_parent() is a bad practice in general, all objects need the same variable name or the component’s code breaks) so i was wondering if there’s a better way to accomodate the values for each case.

This is my current code for a health component:

extends Node2D
class_name HealthComponent

@onready var parent = $"../.."

var maxHealth = parent.maxHealth
var health :float

func _ready():
	health = maxHealth

func SubstractHealth(attack : Attack):
	health = health - attack.attack_damage
	if(health <= 0):
		parent.queue_free()

you can create a initializer-method:

func init(max_health = 100):
    maxHealth = max_health
    health = maxHealth

and then when you instaniate the object you can call this method on the object:

component = component_packed.instantiate()
component.init(component_specific_value)
2 Likes

Instead of a relative path i would just make an export variable and manually select the node for the scene it resides in.

@export var parent : Node

You can narrow the type if you want as well. Like CharacterBody2D/3D

1 Like

So it turns out i was dropped on my head as a toddler because you can make the variable an @export and you should set the value within the object scene, not the level scene, so if anyone is facing the same problem do this and don’t be dumb like me. Also great feedback from everyone who replied

2 Likes

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