Search Unity

Health script

Discussion in 'Scripting' started by Dari, Sep 30, 2013.

  1. Dari

    Dari

    Joined:
    Mar 25, 2013
    Posts:
    130
    Well, I have health script but I want GUI that says how many health is left (GUI box and numbers of your health, not health bar)

    Current script:

    Code (csharp):
    1. var health : float = 100f;
    2. var damagePerShot : float = 50f;
    3.  
    4. function OnTriggerEnter (other : Collider) {
    5.  
    6. if (other.gameObject.tag == "Bullet") {
    7.     health -= damagePerShot;
    8.     Destroy(other.gameObject);
    9.     }
    10. }
    11.  
    12. function Update() {
    13.     if (health <= 0) {
    14.     health = 100f; 
    15.     transform.position.x = 15;
    16.     transform.position.y = 2.5;
    17.     transform.position.z = 28.5;
    18.     transform.rotation.x = 0;
    19.     transform.rotation.y = 180;
    20.     transform.rotation.z = 0;
    21.     }
    22. }
    23.  
    24. function OnGUI() {
    25.     GUI.Box(Rect(0,0,100,100), health);
    26. }
    This isn't working, please help, thanks :)
     
  2. CallumKent

    CallumKent

    Joined:
    Jul 14, 2013
    Posts:
    8
    I'm pretty sure that you have to use a string instead of a float, so you can type in the OnGUI function, var stringHealth : string = health.ToString();
    Then replace health with stringHealth

    So it'd be
    Code (csharp):
    1.  
    2. var health : float = 100f;
    3.  
    4. var damagePerShot : float = 50f;
    5.  
    6.  
    7.  
    8. function OnTriggerEnter (other : Collider) {
    9.  
    10.  
    11.  
    12. if (other.gameObject.tag == "Bullet") {
    13.  
    14.     health -= damagePerShot;
    15.  
    16.     Destroy(other.gameObject);
    17.  
    18.     }
    19.  
    20. }
    21.  
    22.  
    23.  
    24. function Update() {
    25.  
    26.     if (health <= 0) {
    27.  
    28.     health = 100f;  
    29.  
    30.     transform.position.x = 15;
    31.  
    32.     transform.position.y = 2.5;
    33.  
    34.     transform.position.z = 28.5;
    35.  
    36.     transform.rotation.x = 0;
    37.  
    38.     transform.rotation.y = 180;
    39.  
    40.     transform.rotation.z = 0;
    41.  
    42.     }
    43.  
    44. }
    45.  
    46.  
    47.  
    48. function OnGUI() {
    49.    var stringHealth : string = health.ToString();
    50.  
    51.     GUI.Box(new Rect(0,0,100,100), stringHealth);
    52.  
    53. }
    54.  
    EDIT: You need to change Rect to"new Rect"
     
    Last edited: Sep 30, 2013