Python if statement not working as expected. Code 'apparently' called twice
Question: I have this piece of code:

    
    
    import bge
    import GameLogic
    import os
    
    os.system("cls")
    scene = GameLogic.getCurrentScene()
    objects = scene.objects
    objectCube = objects["Cube"]
    visible = objectCube.visible
    if visible == True:
        objectCube.setVisible(False, True)
    else:
        objectCube.setVisible(True, True)
    

This code is supposed to toggle the visibility of an object but instead the
object disappears and immediately reappears in a split second. It looks as if
it just flickers. What am I doing wrong?

Also, don't worry about the other variables, they work fine. I have tested
them using some Console outputs.


Answer: **The problem:** The mouse sensor sends two signals per click, one for mouse
down and one for mouse up. Mouse down sends a positive signal while mouse up
sends negative.

You can test this by holding the mouse button down, the cube will disappear
and when you release the mouse it will return.

**The solution:** Use the sensor's `positive` property to determine if this is
a mouse up or down event.

    
    
    import bge
    import GameLogic
    import os
    
    
    os.system("cls")
    scene = GameLogic.getCurrentScene()
    objects = scene.objects
    objectCube = objects["Cube"]
    visible = objectCube.visible
    
    # get the mouse sensor
    cont = bge.logic.getCurrentController()
    sens = cont.sensors['Mouse']
    if sens.positive: # positive means a down button event
        if visible == True:
            objectCube.setVisible(False, True)
        else:
            objectCube.setVisible(True, True)
    

