So, you want to keep a variable in existance between frames?
You’r last example is half way there:
import bge
cont = bge.logic.getCurrentController()
own = cont.owner
key = cont.sensors['Keyboard']
if not 'count' in own:
own['count'] = 0
if key.positive:
own['count']+=1
Same method applies. You can initiate it in the gameobject by using
if not 'x' in object:
object['x'] = datatype
or, an extension of this:
import bge
class instanceClass:
def __init__(self):
self.x = 1
def main(cont):
own = cont.owner
if not 'instance' in own:
own['instance'] = instanceClass()
#after the code above, if there isn't a registered class already
#it will be created on the gameobject.
#now just use the handle (own['instance']) and modify its attribute (in this case x)
print(own['instance'].x) #get the value of x in the instance
own['instance'].x = 2 #set the value of x in the instance
import bge
cont = bge.logic.getCurrentController()
own = cont.owner
if not "my_key" in bge.logic.globalDict:
bge.logic.globalDict['my_key'] = 0
if cont.sensors[0].positive:
bge.logic.globalDict['my_key'] += 1
GlobalDict is a dictionary, just like the way you store variables on an object. You can treat them the same
A variable lives as long as any reference to the variable exist.
If you reference the variable in a function it will live as long as the function is executed. When leaving the function the variable will die.
The script mode is like a function. After leaving the script all variables die. A variable can survive if you keep a reference somewhere else (module, property etc.). The variable will die with the death of the last reference to it.
Example:
foo = ["demo","list"] # birth of foo
print (foo, id(foo) )
foo.pop()
foo.pop() # remove existing values
foo.extend(["list","with","new","values"]) # add new values
print (foo, id(foo) )
foo = ["other","list"] # foo is dead, long lives foo
print (foo, id(foo) )
# the second foo dies here too