Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Mana problem

Discussion in 'Scripting' started by GodOfMagic, May 20, 2014.

  1. GodOfMagic

    GodOfMagic

    Joined:
    Mar 25, 2014
    Posts:
    34
    Hi,
    Code (csharp):
    1.  
    2. var MP=50;
    3. var req=1;
    4. var Spell=false
    5. function update()
    6. {
    7.    if(Input.GetKeyDown(KeyCode.F))
    8.    {
    9.     Spell = !Spell;
    10.    }
    11.    if(Spell)
    12.    {
    13.    MP -= req*Time.deltaTime;
    14.    }
    15. }
    16.  
    My mana should reduce by 1 each second, but it runs out in few secs instead of 50 secs.
    Can anyone help?
     
  2. MysteriX

    MysteriX

    Joined:
    Apr 8, 2014
    Posts:
    54
    Thats because the function update runs every frame. If you have 25frames/sec it needs 2 sec to reduce your MP to 0.

    EDIT:

    sorry. For this case you use Time.deltaTime... Did not think about it enough... So now i don´t know :/ sorry
     
    Last edited: May 20, 2014
  3. schragnasher

    schragnasher

    Joined:
    Oct 7, 2012
    Posts:
    117
    Code (csharp):
    1.  
    2. float MP=50.0f;
    3. float req=1.0f;
    4. var Spell=false
    5. function update()
    6. {
    7.    if(Input.GetKeyDown(KeyCode.F))
    8.    {
    9.     Spell = !Spell;
    10.    }
    11.    if(Spell)
    12.    {
    13.    MP -= req*Time.deltaTime;
    14.    }
    15. }
    16.  
    Try this, see if it works. Your MP is created as an int, not a float. Setting it to a float value truncates your value.


    int MP = 50;
    MP = MP - 0.5f;
    MP will = 49 not 49.5.

    This is why i always type my variables, "var" annoys me to know end i hate when people use it.
     
    Last edited: May 20, 2014
  4. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    Agree with the above, though I will say that I am a fan of var when used properly (such as when the RHS clearly defines the type for you).