Hi everyone,
there’s been some discussion of late concerning the idea of a “tag” system, which identifies objects has having certain functionality. Whilst there are advantages and disadvantages to this design paradigm, I’ve chosen to include an example for reference
Tagging example***
from collections import defaultdict
class CollectionView:
def __init__(self, data):
self.data = data
def __getitem__(self, key):
return self.data[key]
def __iter__(self):
return iter(self.data)
def __len__(self):
return len(self.data)
def __repr__(self):
return repr(self.data)
class TagManager:
def __init__(self):
self._tags = defaultdict(set)
def associate(self, obj, tag):
self._tags[tag].add(obj)
def disassociate(self, obj, tag):
self._tags[tag].discard(obj)
def with_tag(self, tag):
tags = self._tags.get(tag, set())
return CollectionView(tags)
Components example
***
Whilst I think that tags can be useful for simple queries, if you want to use them for updating the tagged objects in question, rather than using them to find the bosses in the scene, it might make more sense to utilise a system-component design:
In this example, components are defined using linked sensors which support configuration through properties.
Each component must be linked with a sensor (no true pulse), and a name following the convention of
“TAG_” followed by the name of the component, e.g “Input”, written as “TAG_Input”.
The sensor must be created on a separate object - I use empties, and that object is better left unparented from the entity object to avoid wasting calculations on transforms.
The properties set on the component object can be used from within the systems to configure the components.
To create a system, copy the example system in systems.py. Any System subclass in the systems.py file will be automatically added to the system manager).
The “required_components” attribute of the system is a set, which looks like dictionary literal notation, except it is defined in the same manner as a list - curly braces, followed by a comma delimited sequence of names. These are the component names.
Because some systems might require more than one component, when updating the entities, the components associated with the entity corresponds to a dictionary, of the component name followed by the property data. If you have only one component, you still must access it by name within the update loop.
Some of the benefits of ECS designs (avoiding cache misses) are nullified when using Python due to the inability to dictate where memory is allocated, but they can still be a useful abstraction.
Attachments
components.blend (483 KB)