Search Unity

Hunger Bar Script Problem

Discussion in 'Scripting' started by Quist, Jul 24, 2014.

  1. Quist

    Quist

    Joined:
    Feb 25, 2014
    Posts:
    284
    So i want to make a script which will reduce my players hunger by 1 each "etc. third second".
    So i have tried to make a script for it but when i start the game, it just goes from 100 - 0 in like 1 second??
    ---------------------------------------------------------------------------------------------------------------------
    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var MaxHunger = 100;
    4. var Hunger : int;
    5.  
    6. function Start ()
    7. {
    8.     Hunger = MaxHunger;
    9. }
    10.  
    11. function Update ()
    12. {
    13.     Hunger -= Time.deltaTime;
    14.    
    15.     if (Hunger <= 0)
    16.     {
    17.         Dead();
    18.     }
    19. }
    20.  
    21. function Dead()
    22. {
    23.     RespawnMenuV2.playerIsDead = true;
    24.     Debug.Log("Player Died");
    25. }
    26.  
    27. function RespawnStats ()
    28. {
    29.     Hunger = MaxHunger;
    30. }
    31.  
    32. function OnGUI()
    33. {
    34.     GUI.Box(new Rect(10, 10, 50, 20), "" + Hunger.ToString("0"));
    35. }
     
  2. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    Make hunger a float and set it to 100.
     
  3. Quist

    Quist

    Joined:
    Feb 25, 2014
    Posts:
    284
    Thanks dude, it works now :)
     
  4. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    that works as a constant drain on hunger... you stated you wanted it to take one away every third second? is that -1 every 3 seconds?

    Code (JavaScript):
    1.  
    2. //same var declarations
    3.  
    4. function Start(){
    5.     Hunger = MaxHunger;
    6.     InvokeRepeating("GettingHungry", 3, 3);  // could get crazy and do a variable for hungry time to make it changable
    7. }
    8.  
    9. // no more need for an Update Funtion
    10.  
    11. function GettingHungry(){
    12.     Hunger--;
    13.  
    14.     if(Hunger<0){
    15.           CancelInvoke("GettingHungry"); // might as well cancel it if they die
    16.           Dead();
    17.     }
    18. }
    19.  
    20. // the rest is the same
    21.  
    22.  
     
    Last edited: Jul 24, 2014
  5. Quist

    Quist

    Joined:
    Feb 25, 2014
    Posts:
    284
    Yeah that doesnt work since the Health in your shown script isn´t set to anything, but thanks tho :)

    But i have changed the script so instead of doing damage each second, it does -10 damage each 5th second when hunger bar is down at 0, but there are some things that doesnt work, could you please help me, i have set it all up in a new thread here: http://forum.unity3d.com/threads/connection-between-scripts-problem.258805/ :D