I know the practical result is the same, but from a code organization standpoint is it better to have my HealthPack script add HP to my Player object, or is it better for the Player script to add HP to itself upon collision with a HealthPack?
I’m leaning towards keeping this type of logic in the HealthPack script, because if I start adding more types of collectibles to my game the logic in the Player script will become long and harder to keep organized.
Does anyone with more experience have feedback on best practices?
I would agree with you and keep the logic in the HealthPack script.
I would have a Consumable interface that has a “UseConsumable” command on it. The HealthPack adds HP to the player whenever its UseConsumable() command is run.
This way you can have a 100 items do 100 different things, yet the Player does the same thing each time you pick an item up, run UseConsumable().
P.S. At the same time, the player’s health value shouldn’t just be a public integer field that anything can change. We usually have a HealthManager script with Heal, TakeDamage, and other functions/events to make sure we don’t get weird health values.
Thanks for the feedback Garth. Your suggestion to use a “Health Manager” script to prevent the player’s health from being set to weird values is good too.
Another approach would be to have an Actor class that the player and enemies could inherit from that contains a public UpdateHealth method (for changing a private variable where rules could be applied, etc). That could be used to increase or decrease health. Like you could have have enemy projectiles that decrease health.
Then the HealthPack in OnCollisionEnter or OnTriggerEnter could do SendMessage(“UpdateHealth”, HealthPackValue) to heal the player and possibly even enemies (if you want that in your game). The HealthPackValue could be a value you set in the prefab for different types of health packs with different healing values.
A Projectile class’ OnCollisionEnter or OnTriggerEnter could do SendMessage(“UpdateHealth”, DamageValue) to send negative values to whatever it hit. That would handle the player and enemies taking damage from bad things.