Problem when pass values to property when instantiate before add_child

Godot Version

4.4

Question

Im having a trouble to pass a value when instantiate a class
i have a marker 2d to spawwn some troops

extends Marker2D

@onready var troop = preload("res://troop.tscn")

const TYPE: int = 2
func _ready() -> void:
	pass
	
func create_new_troop() -> void:
	print("New tROOP Appears")
	var troop_instance = troop.instantiate()
	troop_instance.position = position
	troop_instance.troop_type = TYPE
	get_parent().add_child(troop_instance)
	#var tr = new troop()

func _on_create_enemy_pressed() -> void:
	create_new_troop();

And this is the class troop where i put a value troop_type


extends CharacterBody2D

const SPEED = 300

var troop_type: int # 1 - Friend Troop 2 - Enemy Troop

func _ready() -> void:
	print(troop_type)

func _physics_process(delta: float) -> void:
	if not is_on_floor():
		velocity += get_gravity() * delta
	
	if troop_type == 1:
		velocity.x = 1 * SPEED
	else:
		velocity.x = -1 * SPEED
	
	move_and_slide()

When execute this is the problem

Solved

Problem was because i need to create a troop access on the Node2d Troop, its parent to my characterBody2d

extends Node2D

@onready var type_troop: int

func _ready() -> void:
	print(type_troop)
	
func get_type_troop() -> int:
	return type_troop

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