Question regarding proper class coding.

Hello, I come from a Java background and am new working with Unity.

Let’s say that I have this gameObject with an Entity component, all Entities must have
a health variable.

In Java, I would have made Health a class and given Entity an instance variable Health, however, If i were to do that to Entity (for example a Health script), I would in fact be able to give the Entity the script, however, I would not be able to modify it for that particular Entity, since it only gives me the option to give it a Health script, but not to modify it.

I guess my question is, In Unity, is it good practice to give the prefab all the components it will need (an Entity component, Health component, Inventory component) etc
instead of giving the Entity component all the instance variables it may make sense for an Entity to have?

Thanks a ton!

Personally, I like my classes to be as concrete as possible, encapsulating all relevant data within. The thought behind that is that any unnecessary dependency on the editor will cause headache. Level designer will forget to add or accidentaly remove required components, and play around with any property exposed in the editor.

Furthermore, your Health class probably does not need a centralized heartbeat, or reaction to physics events ( that’s just following an assumption that an entity handles it’s health rather an the health handling itself ), in which case your health class needs not be a MonoBehaviour.

As for is it wrong to implement it that way? Nope, there’s really no right or wrong here, I’ve seen both practices, and to each his own.

If you do decide to implement the Health as an actual component, keep in mind these pointers:

  1. Cache the instance to the component on startup, rather than calling GetComponent every time you want to access it for better performance.
  2. Maintain dependencies using the [RequireComponent] directive, to make sure you have a health component on every object with additional components that will reference it.

Good luck :slight_smile: