Access specific object when duplicates exist

I have an “enemy character” in my game that is controlled via a python module attached to its physics mesh. The enemy contains this physics mesh, a skeleton, a body mesh, and hurtboxes/hitboxes. I want duplicates of this enemy to exist at once, but I don’t know how to get the python script to access only the parts of the specific instance of the enemy it controls.

For example, I have 2 enemies existing, enemyChar and enemyChar.001 (assuming that’s how the BGE will name duplicates created via the addObject command). I want enemyChar to control its own skeleton, enemySkel. On the other hand, I need enemyChar.001 to control only its skeleton, presumably named enemySkel.001.

How can I get the python script to know which instance of the enemy to control? I know I can use obj.children and obj.getParent to get children and parents, but I have a hard time figuring out how to then access the correct pieces I’m looking for.

Any help would be appreciated!

I suggest to traverse through the parent-child relationship tree. This way you always work with the correct object (do not rely on object names).

An easy way is to mark the root of your characters object tree e.g. with a property.

def getRootOf(gameObject):
    if gameObject is None:
        return None

    if "character root" in gameObject:
        return gameObject

    return getRootOf(gameobject.parent)

Whenever you know a single object of the tree (e.g. as result of a sensor), you can find that root:

if sensor.positive:
    characterRoot = getRootOf(sensor.hitObject)
    if characterRoot:

… and work from there:

def applyDamage(characterRoot):
    skeletons = [child in characterRoot.children if "skeleton" in child]
    sceleton = sceletons[0] # assuming there is always on sceleton

I hope you get the idea