I’m working on a Unity3d game using C#, and we have a lot of situations where we need to access a particular member (say, int health) of a GameObject. We do this using code like:
GameObject obj;
if(obj.GetComponent<Player>() != null) {
obj.GetComponent<Player>().health--;
}
else if(obj.GetComponent<Robot>() != null) {
obj.GetComponent<Robot>().health--;
}
// more painful code
What I’d like to do is have all such classes implement an interface like IHealth, and then do obj.GetComponent<IHealth>().health--;. Is this possible, though? I’ve looked around and it seems like I can’t use an interface as a type parameter.
Why not just have a component
Health. Then attach that to your GameObject, have aRequiresComponentannotation on any scripts that need health, then get it byGetComponent<Health>();(cache it inside the same-object scripts in a private variable)If you have multiple ‘stats’ that are always together, you could make it easier like
I’ve found with unity, this is a surprisingly common ‘problem’. Not sure if it’s a problem because this thinking can really help with some problems…