Hello, new coder here!
I'm writing a code for a farm where carrots grow at random intervals, and once fully grown can be harvested for money. It's been working really well for the most part, but every once in a blue moon I get a message saying it attempted to index a nil value, referring to line 44 and the carrot stops growing until the server is restarted. I'm not really sure why it's doing this, but I'm guessing it has something to do with a debounce or some code being called too quickly as this usually happens if I've been standing on top of that carrot for multiple harvests. If this is the issue, I'm not sure where or why I would need a debounce. Any insight on this would be appreciated!
--Define Starting Variables
local stage = 0
local GrowthTime = math.random(5,15)
--Define Growing function
function growTheCarrot()
if stage == 0 then
script.Parent.CFrame = CFrame.new(script.Parent.Position) + Vector3.new(0, -1.5, 0)
elseif stage > 0 then
script.Parent.CFrame = CFrame.new(script.Parent.Position) + Vector3.new(0, 0.5, 0)
end
end
--Call Grow function and check if ready
function grow()
repeat
wait (GrowthTime)
stage = stage +1
growTheCarrot()
print ("The carrot has grown to Stage "..stage)
until stage == 3
end
--Call for Carrot to grow
growTheCarrot()
grow()
--Add money to player and regrow
script.Parent.Touched:Connect(function(player)
if stage == 3 then
stage = 0
game.Workspace.Swoosh:Play()
print ("Carrot Harvested!")
growTheCarrot()
game.Players:GetPlayerFromCharacter(player.Parent).leaderstats.Money.Value = game.Players:GetPlayerFromCharacter(player.Parent).leaderstats.Money.Value + 1
grow()
end
end)

2 comments
I don't see why you would get a index error. Try printing player.Parent.Name to gives.
also game.Players:GetPlayerFromCharacter(player.Parent) can easily be game.Players[player.Parent.Name]