I know that Stamina shouldnt be nil but it always gives this error:
18:54:57.446 - Players.Player.Backpack.StaminaRegen:14: attempt to index local 'Stamina' (a nil value)
01 | local Player = game.Players.LocalPlayer |
02 |
03 | Player.CharacterAdded:connect( function () |
04 |
05 | Player = game.Players.LocalPlayer |
06 |
07 |
08 | local Stamina = Player.Character:FindFirstChild( "StaminaValue" ) |
09 | local MaxStamina = Player.Character:FindFirstChild( "MaxStaminaValue" ) |
10 |
11 | while wait() do |
12 | if Stamina.Value < MaxStamina.Value then |
13 | Stamina.Value = Stamina.Value + 1 |
14 | wait( 0.01 ) |
15 | end |
16 | end |
17 | end ) |
Please help.
Since you have said you are creating the values with some other code, you should change lines 8 and 9 from this:
1 | local Stamina = Character:FindFirstChild( "StaminaValue" ) |
2 | local MaxStamina = Character:FindFirstChild( "MaxStaminaValue" ) |
To the following
1 | local Stamina = Character:WaitForChild( "StaminaValue" ) |
2 | local MaxStamina = Character:WaitForChild( "MaxStaminaValue" ) |
As the values will be created after Stamina and MaxStamina have been initialised.
Here's your code rewritten a little bit.
01 | local player = game.Players.LocalPlayer |
02 |
03 | player.CharacterAdded:connect( function (newCharacter) |
04 | local stamina = newCharacter:WaitForChild( "StaminaValue" ) |
05 | local maxStamina = newCharacter:WaitForChild( "MaxStaminaValue" ) |
06 | while wait() do |
07 | if (stamina.Value < maxStamina.Value) then |
08 | wait() -- you had wait(0.01) here however the smallest wait time "wait()" is about 0.03 seconds |
09 | stamina.Value = stamina.Value + 1 |
10 | end |
11 | end |
12 | end ) |
1 | local Stamina = Player.Character:FindFirstChild( "StaminaValue" ) |
This variable may pass, but it can still be returned nil! For this to be nil, you are either getting "StaminaValue" from the wrong location, or you are addressing it by the wrong name.
Also, make sure the variable is a intValue, and not a boolean, string, etc. because you can't store numerical values in those.
EDIT: Let me rewrite your code;
01 | local Player = game.Players.LocalPlayer |
02 | local Character = Player.Character |
03 | local Stamina = Character:FindFirstChild( "StaminaValue" ) |
04 | local MaxStamina = Character:FindFirstChild( "MaxStaminaValue" ) |
05 |
06 | Player.CharacterAdded:connect( function () |
07 | while wait() do |
08 | if Stamina.Value < MaxStamina.Value then |
09 | Stamina.Value = Stamina.Value + 1 |
10 | wait( 0.01 ) |
11 | end |
12 | end |
13 | end ) |