get count of instantiated scenes

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lalel345

var scene = preload(“res://Node2D.tscn”)

when I do this add an instance to my current scene.

 func _ready():
    	pass
    
    
    func _physics_process(delta):
    	if Input.is_action_just_pressed("left_click"):
    		var instance = scene.instance()
    		instance.global_position = get_global_mouse_position()
    		add_child(instance)

how do I get the count of the number of instantiated scenes that I have?

:bust_in_silhouette: Reply From: AlexTheRegent
  1. If your scene have only your instanced scenes, you can use get_child_count() method.
  2. Make counter to count instanced and freed instanced (+1 on instance, -1 on free).
  3. Create singleton and add to your instancing scene next code:
func _enter_tree(): 
    Singleton.instances_count += 1

func _exit_tree():
    Singleton.instances_count -= 1

Then Singleton.instances_count will have number of instanced scenes.

but some children are not instances, they are other nodes or other instances I only want to count some certain instances only and others not, not all the instances that are added or entered

lalel345 | 2021-01-04 12:57

:bust_in_silhouette: Reply From: Wakatta

One approach would be to use groups

func _ready():
    pass

func _physics_process(delta):
    if Input.is_action_just_pressed("left_click"):
        var instance = scene.instance()
        instance.global_position = get_global_mouse_position()
        add_child(instance)
        instance.add_to_group("INSTANCE")

and to get the count just use
var count = get_nodes_in_group("INSTANCE").size()

p.s. note that “INSTANCE” can be anything to identify your instances