Issue:
I’d like to have a static field inside a component. I’m trying to figure out if this is going to come back to bite me.
The use case is that I have a component, called Graspable, and a related component called Grasper. Each Graspable instance has a field for a Collider, which I assign in the editor.
Instances of Grasper monitor the collision system by calling Physics.OverlapSphere. When a Grasper detects a Collider nearby, I want it to find the Graspable instance (if any) which is associated with that Collider.
It occurred to me I could maintain a static associative table in Graspable, with Colliders as keys and Graspables as values. Graspable objects can add themselves to the table, and Graspers can use the table to find the Graspable associated with any given Collider. This method would allow me to relate any Graspable to any Collider. I could potentially use a data structure like a hash table to make these lookups efficient.
I am clueless about what problems this is going to create. I just know that using static fields is tricky. Can anybody help me understand whether this is a good idea, and whether I have any other options? I haven’t found another solution that doesn’t involve some sort of static or singleton entity, and this seems to be the most elegant solution I’ve found.
Why I don’t want to use GetComponent:
Here is an example of a reason I don’t want to use GetComponent. The GetComponent family of functions can only obtain components on the same GameObject, or on children or parents of that GameObject. I want to be able to make objects with this structure in the transform hierarchy:
GameObject parent(Graspable, Transform, etc.)
GameObject child1(Collider, Transform)
GameObject child2(Collider, Transform)
GameObject child3(Collider, Transform)
I only want one of the Colliders on the children to be associated with the Graspable component on the parent. To achieve this with GetComponent, I will need to search up the tree with GetComponentInParent, then check the collider field in the Graspable component to see if it matches the collider I’m checking. This means that if there are lots of colliders in close proximity I will be calling GetComponentInParent several times. I don’t want to waste time searching through trees that don’t contain Graspables, which is why I want the relation between a Collider and a Graspable to be efficiently queriable. While I might be able to solve this problem using layer masks, there are a limited number of layers available and I could imagine needing many different systems using this type of functionality.