How to run code when within a certain range of a part

I’m trying to figure out how you can run some code when the player is within a certain range of a part

For example:
If the player is within 128-96, 96-64, etc studs away from a part it will run some code until the player is no longer within that range and what I’m currently trying to do is play a sound If the player is 128-96 studs away then stop the sound if its not within that range and play another sound if the player is within 96-64 studs away and stop the sound if its not within that range. I hope you get what I mean here.

I would greatly appreciate any amount of help! :slight_smile:

1 Like

Just for more info, why do you want to do this? There may be a better way.

You can use .Magnitude or Region3.

Magnitude features are good for this it’s good for radius’ and I use them a lot for e key interactions.

If there is a better way I would love to know it but I’m trying to make like a music system so when you’re getting closer to a part it will play some scary music. I already got the music and stuff I just need to figure out some way to script this into my game.

And how would I use magnitude to script this?

I recommend this as a sample. Vector3 | Documentation - Roblox Creator Hub

Sorry to steal your reply vf but like this:

local soundsByDist = {
    ["rbxassetid://111111"] = {min = 31, max = 50};
    ["rbxassetid://111112"] = {min = 51, max = 70};
}

while wait(0.5) do
    local mag = (emitterPart.Position - charRootPart.Position).magnitude
    for id, info in pairs(soundsByDist) do
        if info.min < mag and info.max > mag then
            for _, v in pairs(emitterPart:GetChildren()) do
                if v:IsA("Sound") then
                    v:Destroy()
                end
            end

            local sound = Instance.new("Sound")
            sound.SoundId = id
            sound.Parent = emitterPart
            sound:Play()
            break
        end
    end
end
1 Like

I have a problem
It keeps playing the sound over and over again and I don’t know how to fix it

ok that should do it, i edited it

1 Like