Alex Alex - 10 months ago 48
C# Question

Unity: Player Stamina and speed manipulation. c#

I've added a stamina to my player where when the stamina bar is empty the player speed's just reduce to 2. And when he collect's a certain powerup it gives him stamina, Now the issue or bug I'm facing, is that when stamina is empty im saying speed = 2; and when i collect the powerup i fill the stamina bar a little bit and return the speed (speed = 7;) the issue is in the other level, in lvl 2 the map is different and the player will change because if i use the same speed amount in map 1 and map 2 then the player will be very fast in map2, that's why my speed is public and i edit it in the inspector. My Questions is. I am hard coding my speed to speed = 7; and this applies to all scenes and level's how can i make the speed more public and i can edit it only for this scene, or a way to say speed = otherSpeed or something idk.

public void AddStamina(int a_staminaToAdd)
// Add stamina when we take coffee.
g_currStamina += a_staminaToAdd;
// Disable the "need stamina: text
g_lowStaminaTxt.enabled = false;


public void DeductStamina(int amount)
// only deduct stamina will player is moving on ground
if (isPlayerGrounded)
// How much stamina are we going to deduct when player is running?
g_currStamina -= amount;
// Change the slider value depending on the stamina
g_StaminaSlider.value = g_currStamina;

if (g_currStamina <= 0 )
//TODO : Go slower
m_speed = 2;
g_currStamina = 0;
g_lowStaminaTxt.enabled = true;
IsStaminaEmpty = true;


g_lowStaminaTxt.enabled = false;


Answer Source

Pull your variables out of the function scope. And add them to the class level.

class foo : monobehaviour
    // Give a default value. This can be changed in the editor
    public int SlowSpeed = 2;
    public int FastSpeed = 7;

    // Your functions somewhere here.

Now that the variables are defined on a class level and are public you can change the values using the editor in unity. By default the 2 and 7 will be used, and if you change any of these values in particular scenes, the values will be applied as you changed them.

Now you would need to change your m_speed = 2; to m_speed = SlowSpeed; for it to work