Check if an object has already been instanced and do not create two of the same time

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

Hello guys; I have a scene 1 that instance a scene 2 randomly; but I want that scene 1 instance only one scene 2 on screen at a time.

Is there any way I can check if the scene 2 instanced by scene 1 is still on screen, before the scene 1 instances a new scene 2 and remain with two scene 2 instanced on the screen?

Something like the “is_playing” that exists in the methods of animation nodes? Scene 1 checks if “is_istanced” and, if yes, does not make a new.

tks guys

:bust_in_silhouette: Reply From: Thomas Karcher

You can assign the instanced scene to a global variable and check the state of this variable before creating a new instance:

var scene_2 : Node2D 

func remove_scene_2():
	if is_instance_valid(scene_2):
func add_scene_2():
	# only instance a new scene 2 if there is none yet
	if !is_instance_valid(scene_2):
		scene_2 = preload("res://Node2D.tscn").instance()
		print ("Scene 2 was already instanced before")

Thanks Thomas;

Solved the problem

lucasfazzi | 2019-07-05 17:07