Search code examples
luaroblox

Having issues with Region3 in roblox lua


I have been trying to work on a Region3 script were when you are in it, it plays a song. But I've come across 2 issues, 1 being it thinks the player is always in it when you the player isn't. And the second being the script runs so fast that it keeps repeating before anything can happen

local RegionPart = game.Workspace.RegionArea
local pos1 = RegionPart.Position - (RegionPart.Size / 2)
local pos2 = RegionPart.Position + (RegionPart.Size / 2)
local Region = Region3.new(pos1, pos2) 

while true do 
    wait()
    local burhj = workspace:FindPartsInRegion3(Region, nil, 1000)
        local song = game.Workspace.bb
        song:Play()
        print("THE SCRIPT WORKS!")
    end

Solution

  • You query the objects which are in Region, but never used the result and just continued. Loop over burhj and check for valid parts.

    In this forum the use of FindFirstChild is suggested:

    for i,v in ipairs(burhj) do
        local player = v.Parent:FindFirstChild("Humanoid")
        if player then
           print("player is in region: " + player.Parent.Name)
        end
    end
    

    Alternatively, you can directly use the player position, if the player object or position is known:

    local pos = yourPlayer.HumanoidRootPart.Position
    local center = region.CFrame
    local size = region.Size
    if pos.X > center.X - size.X / 2 and pos.X < center.X + size.X / 2 and ... then
       print("player is in region")
    end
    

    A helper function, if not already present, might be helpful.

    For the second problem, set a flag if the player is in the region. Play the sound when the flag was not already set. Unset the flag if you leave the region.

    --here are your vars
    local enteredFlag = false
    while true do 
        wait()
        if playerIsWithinRegion then --here come whatever approach you chose earlier
            if not enteredFlag then
                enteredFlag = true
                local song = game.Workspace.bb
                song:Play()
                print("THE SCRIPT WORKS!")
            end
        else
            --no player is in the region, lets reset the flag
            enteredFlag  = false
        end
    end