Hi i’m trying to get objects by name and properties but it doesnt work. Whats wrong with my code?
for obj in objs:
if 'MenuItem' in obj and obj == active_item:
Name of property is ‘MenuItem’ and variable ‘active_item’ is exactly the same as the object name. If i search only for the property name it works. No error in console, btw.
Since you’re looking for a name, shouldn’t it be…
if 'MenuItem' in obj.name
Works for me.
@gull1ver is almost correct.
Because you look for the property the first part is correct, the second part needs the .name
and obj.name == active_item
why? obj is a kx_gameObject, object.name is the obj name as a string, active_item is also a string. so that should work.
Ah, haha. I didn’t realize this was a game engine thread.
Remember that you could write all those lines in a single line by using list comprehensions:
objects_list = [obj for obj in objs if 'MenuItem' in obj and obj.name == active_item]
This creates a list of all the matching objects.
that would just make the code hard to read.
using a for loop is easier to read, but slightly slower than list comprehension
(for bigger list it can add up quite a bit also)
That is indeed better in most cases but not all. In single pulse mode (or for creating that list once) it’s best to do it that way. But if you use it in true pulse, a simple for loop is faster and lighter to use.
The reason behind it is easy, 1 less loop trough all the objects.
objects_list loops trough all objects, then you need another loop to get trough that list, while you can grab it in one single loop.
When you worry about readability place the code into a function with an understandable name. E.g. “filterByNameAndProperty” (or “filter_by_name_and_property”).
The code could look like that:
candidates = filterByNameAndProperty(objects, active_item, "MenuItem")