Gamespace: Health Bar
I decided to add a health bar so that when the player collides with an enemy, they lose health.
When the health point value is equal to zero, the Gamespace restarts.
Health Bar Game View |
The health bar gameObject held the foreground and background for the health bar.
This is the inspector for the background used in the health bar.
The background is only shown when the player loses health as the foreground bar decreases in length.
The colour has been changed to a dark grey to fit the sky theme.
Background Bar Inspector |
This is the inspector for the foreground bar used in the health bar.
This bar decreased in length when the player loses health.
The X Pivot has been set to zero so that when the player loses health, the bar only decreases in length from right to left.
When the bar does not exist anymore, the player's health is at zero and the Gamespace restarts.
Foreground Bar Inspector |
The 'HealthBar' script has three variables declared.
The two float variables 'maxHealth' and 'health' have been made public meaning that their values can be edited outside of the script (In the inspector).
The rectTransform variable 'barTransform' has also been made public.
The float variable 'healthRatio' has been declared privately in the Update() function meaning that this value cannot be edited outside of the script.
The value that will be assigned to the 'healthRatio' variable is equal to the health (set in the inspector) divided by the maxHealth (also set in the inspector).
The bar is scaled accordingly using the RectTransform type that the 'barTransform' variable is set as.
The bar is transformed in localScale and the scale/position equals a new 3D vector where the X-axis is scaled using the 'healthRatio' variable, and the Y and Z-axis is equal to one.
The 'TakeDamage' function is public meaning that it can be accessed in another script.
The 'damage' variable has been passed by parameter to this script and is used to determine the value that will be assigned to the 'health' variable. The 'health' variable is equal to the current health minus the damage the player has taken.
Comments