Checking if object property starts with a certain name

I make a script with some code like this for example:

import bge
from bge import logic as logic

controller = logic.getCurrentController()
owner = controller.owner
scene = logic.getCurrentScene()
objects = scene.objects
collision_sensor = controller.sensors[“collision_sensor”]
hitObjectList = collision_sensor.hitObjectList
hitObject = collision_sensor.hitObject
propName = owner.getPropertyNames()

if not hitObject.startswith(“property”):
print(“example message”)

The line where it says “startswith()” is where it spits out the error, this didn’t happen in 2.49, is there any other way to check if the property on the object starts with a certain name, like name_ or anything else?

This confuses me…:confused:

hitObject is a GameObject.
.startswith works on strings.

You can guess the problem with hitObject.startswith(prefix). Even in 2.49 it would be weird (maybe it was using the name implicitly ?)
Anyway there is indeed a problem.

owner.getPropertyNames() returns a LIST of STRINGS corresponding to the OWNER property names.
You can use a for loop to parcour each string:


for property_name in owner.getPropertyNames():
    if property_name.startswith(prefix):
        do_thing()
        break # optional

I’d just check if the key I’m looking for exists and be done with it, seems cleaner to me.


key = prefix+suffix

try:
     if key in obj:
        #codestuff
except:
     print('Sorry doc, no such prop in '+ object')

import bgefrom bge import logic as logic


controller = logic.getCurrentController()
owner = controller.owner
scene = logic.getCurrentScene()
objects = scene.objects
collision_sensor = controller.sensors["collision_sensor"]
hitObjectList = collision_sensor.hitObjectList
hitObject = collision_sensor.hitObject
propName = owner.getPropertyNames()


if not hitObject<b>.name.</b>startswith("property"):
    print("example message")

You need to add the “.name” property, because a game object doesn’t have the function “.startswith” but it’s name does.

Note that your code does different to what the thread title implies. Also note that hitObject can be None, so you may need a check to guard against that.

That solved it for me.:wink: