Python count

Okay I’m still stuck I tried posting in the simple questions but got no answers so thought i’d try here.
I want a variable to start at 0 and add 1 to it each time it gets an input, i.e. it keeps track of how many times it’s been triggered.
My code:

variable = 0
if sens.isPositive():
    variable += 1
print variable

My output 1 , 1 , 1 exctera for however many times.
My desired output 1 , 2 , 3 exctera for however many times
I can see why this issue occurs but can’t see how to solve it, and no I don’t want to use properties.

Well, I can tell you how, but you might not like it depending on why you don’t like using properties. There are two ways I generally do this sort of thing:

  1. The first uses global variables stored in “GameLogic”:

if not hasattr(GameLogic,"variable"):      #this checks to see if the variable exists 
    GameLogic.variable = 0                   #if not, it declares it and stores it in GameLogic
if sens.isPositive():
    GameLogic.variable += 1
print GameLogic.variable


An optional version would be to put the first part where the variable is initiated in a sort of “Initiate” or “Startup” script that runs at the beginning of the game. Once initiated, the variable will be globally available at any time in any scene or script by using “GameLogic.variable”

NOTE: If multiple objects are running this script, they will only affect this one variable.

  1. The next method is a per-object method:

owner = GameLogic.getCurrentController().getOwner()
if not hasattr(owner,"variable"):  #does the same thing as above
     owner.variable = 0
if sens.isPositive():
     owner.variable += 1
print owner.variable

Any object running this script will have its own value for “variable” (i.e. you can see how many times the sensor was fired for each object). Basically, this is essentially giving the object a property in script rather than using the editor (which is why you might not like it).

Anyway, hope that helps.

Thanks that’ll do me, It was more that I wanted to know how to acheive the affect without properties than couldn’t use them period.

Oh, ok. No problem–glad to help.