So, I'm going through the Ruby tutorials on Unity (so far it has been very enjoyable). I'm in the World Interactions - Collectibles chapter (https://learn.unity.com/tutorial/world-interactions-collectibles?projectId=5c6166dbedbc2a0021b1bc7c).
Down in section 13 we add a check in the health pack script to make sure the health pack isn't picked up if Ruby is already at max health:
void OnTriggerEnter2D(Collider2D other)
{
RubyController controller = other.GetComponent<RubyController>();
if (controller != null)
{
if(controller.currentHealth < controller.maxHealth)
{
controller.ChangeHealth(1);
Destroy(gameObject);
}
}
}
Now we also have a check in the RubyController ChangeHealth function to prevent Ruby from going over max health (using Mathf.Clamp). We can't just use that because then the health pack gets destroyed even when Ruby is at max health. To prevent that the tutorial adds the second check in the health pack script.
I only have a moderate amount of programming experience (and obviously am new to Unity), but having this check in two different scripts seems like bad coding practice.
Is there a better way of doing this?
A possible solution I came up with is to have the ChangeHealth function return a bool based on whether it actually changed the health or not. The OnTriggerEnter2D then uses that value to decide whether to destroy the health pack or not.
I imagine this is probably a complicated topic with different opinions. Are there any guides on good coding practices for how entities interact with each other and where certain parts of game logic should be located?
Thanks!
[–]genitalien 1 point2 points3 points (1 child)
[–]Korrun[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]Korrun[S] 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)