Child By Name Tutorial

Abstract

With carefull naming we can easly get the child of an object.

Instructions

Lets say we have an object named 'Thingy' with two children, 'Thingy Display' and 'Thingy Sensor'. Maybe we duplicated it so that now theres a second object with the name 'Thingy.001' with the children 'Thingy Display.001' and 'Thingy Sensor.001'. We can get the objects children with the following code.

Prerequisites

str.split

Code

def child(obj, child):
  # If an objects name has a period in it then we split off the period.
  name = obj.name.split('.')
  # We try to make a suffix by taking the string after the period and adding a period to it.  Maybe this could be done better?
  try:    suffix = '.'+name[1]
  # If theres no period then we define the suffix as no string.
  except IndexError: suffix = ''
  # We return the child of the object that has the full name of the parents name plus the child's name plus the parents suffix.
  return obj.childrenRecursive[name[0] +' '+child+ suffix]

Usage

from somewhere import child
own = bge.logic.getCurrentController().owner
# If own.name == 'Thingy.001' then this returns the object 'Thingy Display.001'
childObj = child(own, 'Display')

Questions

Create an account and edit this post to ask or answer questions.

Further Reading

String Methods

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License