Random Number PlayerStat Adder

I have an issue.

I have been working with my friend who is a scripter, and neither of us could figure out how to do this.

We are essentially trying to make it so that when you touch a part it activates a script, and when you are touching the part, it picks between 1-2, and if the number is one, it picks between 1-30 and adds that number to a PlayerStat named “Gems.” And if the number is 2, it picks a number between 31-100 and adds the number to Gems, and it then waits 30 seconds and does it again.

Asking for help here, we have tried everything, and I can’t find any posts about things like this. How can we do this? Any ideas?

Let’s break this down.

To run code whenever a player is touching a part. You write the following:

part.Touched:Connect(function(touching)
    if touching.Parent:FindFirstChild("Humanoid") then
        -- checks if the part touching is a player
    end
end)

After this, we try to find a random number from 1 to 2. So inside the if statement we write the following:

local num = math.random(1,2)
if num == 1 then
    -- code for when num is 1
else
    -- code for when num is 2
end

In these if statements, we write the following:

if num == 1 then
    local num = math.random(1,30)
    touching.settings.Gems = touching.settings.Gems + num -- Adding gems
else
    repeat wait(30)
      local num = math.random(31,100)
      touching.settings.Gems = touching.settings.Gems + num -- Adding Gems
    until touching == nil
end

Hopefully this solves your problem! If you have any problems let me know

1 Like

So I talked to my friend, and they said that when they tried to implement it the values kept coming out as around 415 and 501 and numbers like that whenever they touched it. This is the screenshot they sent me:
image

Do you know how to fix this?

To add to this, it added the Value but repeated it about 10 times. Which was the same problem I had while trying to script this system.

1 Like

Weird… Did you try printing variable num in the repeat loop?

1 Like

I will try that now. I’ll reply with the output

1 Like

image
image

This is the output.

1 Like

Does this output print every 30 seconds?

1 Like

Yea, I’ve been letting it run for a couple of minutes and I’ve gained about 2000-3000 gems. Currently at 43,000.

1 Like

Was the code repeating itself about 10 times in that loop?

1 Like

Yes, it repeats every time the code runs.

1 Like

Okay I figured this out. Every single body part is touching the brick which fires the Touched event more than once.

So you might wanna add a debounce to the event

1 Like

Oh, that explains it. Thanks for the help!

2 Likes

Thanks for your help! Now we can actually finish the part of the map!

1 Like

You should use a debounce in a Touched event regardless of if one or more limbs of a player’s character model is touching the part, Touched regularly misfires (or at the very least fires when you wouldn’t expect it to).