#Counting number of instances currently spawned

2 messages · Page 1 of 1 (latest)

turbid finch
#

Hi everyone, I just completed the vampire survivor exercice : https://www.youtube.com/watch?v=GwCiGixlqiU&list=LL&index=1&t=6038s

I'm trying to customize it so it does the following :

  • Trees spawning randomly around the player

My problem is :

  • I need to control the maximum amount of trees on the screen. I'm stuck with this.

Here is my code :

extends Node2D

func _ready():
spawn_mob()
spawn_mob()
spawn_mob()
spawn_mob()

func _on_timer_timeout():
spawn_mob()
spawn_tree()
spawn_tree()
spawn_tree()
spawn_tree()

func _on_player_health_depleted():
%GameOver.visible = true
get_tree().paused = true

func spawn_mob():
var new_mob = preload("res://mob.tscn").instantiate()
%PathFollow2D.progress_ratio = randf()
new_mob.global_position = %PathFollow2D.global_position
add_child(new_mob)

func spawn_tree():
var new_tree = preload("res://pine_tree.tscn").instantiate()

#Generate random x and y coordinates around player
var random_x = randi_range(-2000 + %Player.position.x , 2000 + %Player.position.x)
var random_y = randi_range(-1100 + %Player.position.y ,1100 + %Player.position.y)

Give new_tree the random_position

var random_position = Vector2(random_x, random_y)
new_tree.position = random_position

#Adding the instance into the PineTreeGroup (Is that the way ?)
new_tree.add_to_group("PineTreeGroup")
add_child(new_tree)

#trying to count the number of PineTree instances and printing it
var PineTreeGroup = get_node("PineTreeGroup")
var count = PineTreeGroup.get_child_count()
print("Nombre d'arbre :", count)

I currently have this error :

  • Attempt to call function 'get_child_count' in base 'null instance' on a null instance.

Any idea ?

glass fiber
#

basically what the error is telling you is that by the time it attempts to use the "child_count" the PineTreeGroup doesn't exist. That is mainly because PineTreeGroup is a ... group... not a node. A group is like a tag, or a name, not exaclty something you can call or summon the same way you would summon a node.