addScene and scene.end() problem

I have a .blend with Scene1 and Scene2, when press space toggle scene2 and add or end it
Active’s scene is Scene1

Scene1 have an always sensor with a python script


import bge

class Scene1():

    def update(self):

        keyboard = bge.logic.keyboard
        JUST_ACTIVATED = bge.logic.KX_INPUT_JUST_ACTIVATED

        if keyboard.events[bge.events.SPACEKEY] == JUST_ACTIVATED:
            if(len(bge.logic.getSceneList())<2):
                print("Opening scene2!")
                bge.logic.addScene("Scene2",0)
            else:
                print("Removing scene2")
                bge.logic.getSceneList()[0].end()

scene = Scene1()

def update():
    scene.update()

The same for Scene2


import bge

class Scene2():

    def update(self):
        print("I'm scene2")


scene = Scene2()
print("Before update scene")

def update():
     scene.update() 


So I press space and this is the print (add scene2 and run his update)

Opening scene2!
Before update scene
I'm scene2
I'm scene2
I'm scene2
I'm scene2
I'm scene2
I'm scene2
I'm scene2
I'm scene2
...

Press again and (scene2 end)


Removing scene2

Press one more time and (add scene2 again but… here is my problem)


Opening scene2!
I'm scene2
I'm scene2
I'm scene2
I'm scene2
...

Why not print ‘Before update scene’?
Blend attachments:
bug.blend.zip (71.2 KB)

this another question

You’re running the code in module mode, which means it only runs the body of the module once. You should typically avoid having global variables in scripts unless there’s a compelling reason to do so.

Instead, do something more like this


import bge


class Scene2():


	def update(self):
		print("I'm scene2")




def update(cont):
	own = cont.owner
	
	try:
		my_scene = own['scene']
	except KeyError:
		my_scene = own['scene'] = Scene2()
		
	if(bge.logic.globalDict["var"]):
		my_scene.update() 


Thanks!! Works fine :slight_smile: