Super simple python question...

Let’s just say I’ve got a script something like this:

def main():
    cont = bge.logic.getCurrentController()
    own = cont.owner

    x = 0

    hit = cont.sensors['Collision']
    bounce = cont.actuators['Motion']


    if hit.positive and x<5:
        cont.activate(bounce)
        x = x + 1
    else:
        cont.deactivate(bounce)


main()

So what I’m trying to do is get it to stop after five bounces. (duh), but, Of course, you see the problem. It keeps making x = 0. If I get rid of the x = 0, then I’m referencing it before assigning it, and i’ll have problems. So, what’s a way to solve this?

(Other than using a global variable or something - there’s gotta be a better way than that.)

All advice is welcome, simplest solutions preferred.

You can try to put the variable x inside the owner object like own[“x”] = 0 but you have to initalize it before using by using either an initialization state or the usual thing i have seen people do


if not "init" in obj:
    #do initializations
    obj["init"] = true
else:
    #your code

or even simply


if not "x" in obj:
    #do initializations
    obj["x"] = 0
else:
    #your code

Hi dragonspammer,

When you put this on top of the script outside the module, it will only run one instance, perfect for initializing. Did you know that if you define a module you automatically get the controller too? Also the syntax of Python permits you to shorten some calculations. I would also suggest to use the module type instead of script type because it’s cleaner this way. You would be needing extra lines if you would be running as a script:

from bge import logic
cont = logic.getCurrentController()
main(cont)

Now you only need this:

x = 0

def main(cont):
    own = cont.owner
    hit = cont.sensors['Collision']
    bounce = cont.actuators['Motion']

    if hit.positive and x<5:
        cont.activate(bounce)
        x += 1
    else:
        cont.deactivate(bounce)

EDIT: Using a Property, as anurag.k suggested is also a valid solution. This is especially handy if you need access to the Property’s value.

just as alternative i guess you can use the distance to the obj hit (so the physic as a timer) , but this mean that you have to grab the reference and store it somewhere.

so, there ever something to store

YESSS!!! THANK YOU ALL! I GOT IT WORKING!

The blender community is just awesome!!!

Oh, actually you don’t even need the line: own = cont.owner, because you are not using it.