Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Adding a HealthBar

Discussion in 'Editor & General Support' started by GameMakerGuy1234, Jun 7, 2019.

?

How do I insert a working health bar into this code?

Poll closed Jun 14, 2019.
  1. Add an additional variable called public Text healthbar;

    0 vote(s)
    0.0%
  2. Add a UI Image

    0 vote(s)
    0.0%
Multiple votes are allowed.
  1. GameMakerGuy1234

    GameMakerGuy1234

    Joined:
    Jun 29, 2015
    Posts:
    1
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.SceneManagement;
    6. using UnityEngine.UI;
    7.  
    8. [RequireComponent(typeof(CharacterController))]
    9. public class PlayerControl : MonoBehaviour
    10. {
    11.  
    12.     public float movementSpeed = 20f;
    13.     public float jumpSpeed = 8.5f;
    14.     public float autoRespawnPoint = -50f;
    15.  
    16.     public GameObject PauseMenuCanvas;
    17.     public GameObject bulletPrefab;
    18.     public Transform bulletSpawn;
    19.     public Text healthText;
    20.     public Texture2D crosshairTexture;
    21.  
    22.     private float crosshairScale = 1;
    23.     private float mouseSensitivity = 2f;
    24.     private float fireRate = 0.4f;
    25.     private float bulletSpeed = 20f;
    26.     private float nextFire;
    27.  
    28.     // public GameObject bulletPrefab;
    29.     // public Transform bulletSpawn;
    30.  
    31.     private float upRange = 65f; // you can make this public
    32.     private float pitch = 0;
    33.     private float drag = 1;
    34.     private float verticalVelocity = 0;
    35.     private int health = 10;
    36.     private float trampolineVelocity = 0f;
    37.     private IEnumerator coroutine;
    38.     CharacterController cc;
    39.  
    40.     private void Start()
    41.     {
    42.         Cursor.lockState = CursorLockMode.Locked;
    43.         Cursor.visible = false;
    44.         PlayerPrefs.SetInt("currentLevel", SceneManager.GetActiveScene().buildIndex);
    45.         if (Application.platform == RuntimePlatform.WebGLPlayer)
    46.         {
    47.             mouseSensitivity = 0.4f;
    48.         }
    49.         cc = GetComponent<CharacterController>();
    50.         PauseMenuCanvas.SetActive(true);
    51.         Text LevelCodeText = GameObject.Find("LevelCodeText").GetComponent<Text>();
    52.         int levelCode = SceneManager.GetActiveScene().buildIndex - 2;
    53.         int text = PlayerPrefs.GetInt("Level_Code_" + (levelCode));
    54.         LevelCodeText.text = "Level Code: " + text;
    55.         PauseMenuCanvas.SetActive(false);
    56.         Time.timeScale = 1f;
    57.     }
    58.     void Update()
    59.     {
    60.         if (Input.GetKeyDown(KeyCode.Escape) || Input.GetKeyDown("p"))
    61.         {
    62.             if (Time.timeScale == 0f)
    63.             {
    64.                 Time.timeScale = 1f;
    65.                 PauseMenuCanvas.SetActive(false);
    66.                 Cursor.lockState = CursorLockMode.Locked;
    67.                 Cursor.visible = false;
    68.             }
    69.             else
    70.             {
    71.                 Time.timeScale = 0f;
    72.                 PauseMenuCanvas.SetActive(true);
    73.                 Cursor.lockState = CursorLockMode.None;
    74.                 Cursor.visible = true;
    75.             }
    76.         }
    77.     }
    78.  
    79.     void FixedUpdate()
    80.     {
    81.  
    82.         // Rotation
    83.  
    84.         float yaw = mouseSensitivity * Input.GetAxis("Mouse X");
    85.         pitch -= mouseSensitivity * Input.GetAxis("Mouse Y");
    86.         pitch = Mathf.Clamp(pitch, -upRange, upRange + 20f);
    87.         transform.Rotate(0, yaw, 0);
    88.         Camera.main.transform.localRotation = Quaternion.Euler(pitch, 0, 0);
    89.  
    90.         // Movement
    91.         if (cc.isGrounded)
    92.         {
    93.             drag = 0.7f;
    94.         }
    95.         else
    96.         {
    97.             drag = 0.5f;
    98.         }
    99.         float forwardSpeed = Input.GetAxis("Vertical") * movementSpeed * drag;
    100.         if (forwardSpeed < 0)
    101.         {
    102.             forwardSpeed = forwardSpeed * 0.8f;
    103.         }
    104.         float sideSpeed = Input.GetAxis("Horizontal") * movementSpeed * 0.9f * drag;
    105.         if (transform.position.y < autoRespawnPoint) // AUTO RESPAWN
    106.         {
    107.             SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    108.         }
    109.         if (!cc.isGrounded)
    110.         {
    111.             verticalVelocity += Physics.gravity.y * 2 * Time.deltaTime;
    112.             trampolineVelocity = 0f;
    113.         }
    114.         else
    115.         {
    116.             // you can also use GetButtonDown to disable bunny hopping
    117.             verticalVelocity = trampolineVelocity;
    118.             if (Input.GetButton("Jump")) { verticalVelocity += jumpSpeed; }
    119.         }
    120.         Vector3 speed = new Vector3(sideSpeed, verticalVelocity, forwardSpeed);
    121.         speed = transform.rotation * speed; // gets direction relative to player
    122.  
    123.         cc.Move(speed * Time.deltaTime);
    124.  
    125.         // Shooting
    126.         if (Input.GetButton("Fire1") && Time.time > nextFire)
    127.         {
    128.             Fire();
    129.         }
    130.     }
    131.     private IEnumerator UpdateHealth()
    132.     {
    133.         healthText.text = "Health: " + health;
    134.         healthText.color = Color.red;
    135.         yield return new WaitForSeconds(0.4f);
    136.         healthText.color = Color.black;
    137.     }
    138.     private void OnControllerColliderHit(ControllerColliderHit hit)
    139.     {
    140.         GameObject body = hit.collider.gameObject;
    141.         if (body.CompareTag("Trampoline"))
    142.         {
    143.             trampolineVelocity = 20f;
    144.         }
    145.  
    146.     }
    147.  
    148.     private void OnCollisionEnter(Collision col)
    149.     {
    150.         if (col.gameObject.tag == "EBullet")
    151.         {
    152.             if (health <= 1)
    153.             {
    154.                 SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    155.  
    156.             }
    157.             else
    158.             {
    159.                 health -= 1;
    160.                 StartCoroutine(UpdateHealth());
    161.             }
    162.         }
    163.     }
    164.  
    165.     private void OnTriggerEnter(Collider other)
    166.     {
    167.         if (other.gameObject.CompareTag("AutoRespawnUpdater"))
    168.         {
    169.             // autoRespawnPoint -= 10;
    170.             autoRespawnPoint = System.Int32.Parse(other.gameObject.name);
    171.             Destroy(other.gameObject);
    172.         }
    173.         else if (other.gameObject.CompareTag("CheckPoint"))
    174.         {
    175.             SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
    176.         }
    177.     }
    178.  
    179.     void Fire()
    180.     {
    181.         nextFire = Time.time + fireRate;
    182.         GameObject bullet = (GameObject)Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
    183.         bullet.transform.Rotate(Vector3.right * 90);
    184.         bullet.GetComponent<Rigidbody>().AddForce(bulletSpawn.transform.forward * bulletSpeed, ForceMode.Impulse);
    185.         // bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 6;
    186.         Destroy(bullet, 1.0f);
    187.     }
    188.  
    189.     void OnGUI()
    190.     {
    191.         //if not paused
    192.         if (Time.timeScale != 0)
    193.         {
    194.             if (crosshairTexture != null)
    195.                 GUI.DrawTexture(new Rect((Screen.width - crosshairTexture.width * crosshairScale) / 2, (Screen.height - crosshairTexture.height * crosshairScale) / 2, crosshairTexture.width * crosshairScale, crosshairTexture.height * crosshairScale), crosshairTexture);
    196.             else
    197.                 Debug.Log("No crosshair texture set in the Inspector");
    198.         }
    199.     }
    200. }
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106