Controller script - Singleton

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

Okay I am new to Godot and have the latest release 3.1 and I am developing on Windows 10 operating system.

This project is a simple copy of the original space invaders video game. At the moment I have two scenes one called Game (Node node) and another called Invader (KinematicBody2D node). The Game is the main scene and contains an Area2D node used to define the Invader area.

The Invader scene is instantiated by the Game node using:
Export (PackedScene) var Invader

var invader = Invader.instance()

I add 5 rows of these Invaders to the Game Scene. This all works fine but as I march them across the Invader area I wish them to reverse direction, when the farthest Invader exits the area. I use the Body Exited Signal to trigger this occurrence – to the Game script. This is also working fine.

However what is not working – at least as expected – is a Singleton script which I created which contains a flag telling the Invaders when to reverse the direction of their march. The script is called Controller and has a single variable flip.

Now this is what I do not understand, when the Invaders trigger the Body Exited Signal only the FIRST Invader that was instantiated reverses direction all the others continue to march on. The march method is found in a script attached to the invader KinematicBody2 node (Invader Scene). This method has a simple condition statement like – if Controller.flip = true :
else :

What am I missing. I have used a Controller Singleton in the past in an earlier version of Godot and this is the first time I have not understood the result.

Your assistance would be greatly appreciated.


Please share your project, missing context.

flurick | 2019-03-31 10:57

:bust_in_silhouette: Reply From: ZBot

Is your singleton added via the Autoload function on Project settings or added to an object?

Autoload function on Project settings.


throwcode | 2019-04-01 01:12

I suspect the autorun process has 1 global value flip which decides what direction do the instanced enemies go the moment one body exits the variable gets changed in your singleton, the variable changed for everyone not just the enemy that exited. That is why they all changed directions.

You need either a local variable which only gets declared when the signal is received.
Or if you wanna use the singleton you need a variable in the singleton for each enemy that gets instanced in the scene.

Depending on what you want or how you want to do it. You can disconnect the signal after a while, use a custom signal.

Hope this helps.

ZBot | 2019-04-01 13:55