Hello!
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
UIS.InputChanged:Connect(function()
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)
end
end)
end
end
end)```
--Server script
```lua
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
end)```
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.
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.
You don’t actually need InputChanged here. Rather just check the mouse.Target once input happens in InputBegan.
local validTargets = {
'Leaf',
'Leaves',
'PinkPlant'
}
-- 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)
end
end
end
end)