Script gives stupidly high number and I'm not sure why

I am currently trying to make it so if you pick up leaves then it gives you a random number of leaves. It works but for some reason instead of giving a number between 1, 4 it gives an extremely high number like 500. It seems that the longer you move your mouse on the object the higher the number goes.

–Local script

	if mouse.Target then
		if mouse.Target.Name == 'Leaf' or mouse.Target.Parent.Name == 'Leaf' or mouse.Target.Name == 'Leaves' or mouse.Target.Parent.Name == 'Leaves' or mouse.Target.Name == 'PinkPlant' or mouse.Parent.Target.Name == 'PinkPlant' then
			UIS.InputBegan:Connect(function(input, IsTyping)
				if input.KeyCode == Enum.KeyCode[key] and not IsTyping then
					local randomLeaves = math.random(1,4)
					local randomPetals = math.random(1,4)
					replicatedStorage.EnviromentEvents.Fibre:FireServer(randomLeaves, randomPetals)

--Server script
local replicatedStorage = game:GetService("ReplicatedStorage")

local enviromentEvent = replicatedStorage.EnviromentEvents.Fibre

enviromentEvent.OnServerEvent:Connect(function(player, randomLeaves, randomPetals)

player.leaderstats.Leaves.Value += randomLeaves

player.leaderstats.Petals.Value += randomPetals


Thanks for reading

I think it might be because .InputChanged fires tons when the button is held down. Try .InputBegan instead, it should only fire once when an input is received.

Your code has a few issues.

  1. You’re creating a memory leak. Every time input changes (mouse moves, a key is pressed, etc.) you’re connecting to the InputBegan event. These connections aren’t being garbage collected. This is really bad.
  2. You don’t actually need InputChanged here. Rather just check the mouse.Target once input happens in InputBegan.
local validTargets = {

-- Listen for when input begins
UIS.InputBegan:Connect(function(input, gpe)
  if (gpe) then return end -- Ignore game processed events (such as typing)

  -- The target or the parent of the target's name must be in the table
  if (table.find(validTargets, mouse.Target.Name) or table.find(validTargets, mouse.Target.Parent.Name)) then
    -- We're specifically looking for keyboard input
    if (input.UserInputType == Enum.UserInputType.Keyboard) then
      -- Now verify that the key is correct
      if (input.KeyCode == Enum.KeyCode[key]) then
        local randomLeaves = math.random(1, 4)
        local randomPetals = math.random(1, 4)
        replicatedStorage.EnviromentEvents.Fibre:FireServer(randomLeaves, randomPetals)

If you want more information consult the UserInputService DevHub page.

1 Like

Thank you, this works but now everytime I do something after picking it up it prints this

Players.Coder_Tom.PlayerScripts.mainPickup:40: attempt to index nil with ‘Name’

My mistake I forgot to check if mouse.Target was nil so right after ignoring game processed events just add this line:

if (mouse.Target == nil) then return end -- Ignore a nil target
1 Like