Comments

  • The fValue private float variable stores the health value itself. It's declared with two C# attributes: SerializedField (to show the value in the Inspector) and Range, to display as a slider.
  • The fValue variable is accessed through the Get and Set methods for a C# property. The Get method simply returns fValue. The set method updates the value and validates it.
  • The Set method invokes the HealthChanged event, since the health has changed, and if the health equals or falls below zero, the HealthExpired event is invoked, allowing any visually scripted events in the object Inspector to run.

With the Health script coded, you can now attach it to any object that should have a health property, including the player and all of his/her enemies. ...

Get Mastering Unity 2017 Game Development with C# - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.