Can I optimize this region code?

  • What does the code do and what are you not satisfied with?

    I want to make a code that checks if the player got out from the region but it’s too complex and I think it can be optimized.

  • What potential improvements have you considered?

    I don’t know maybe region3 but the only way to know if the part is in region3
    is by using GetPartsInRegion3()

  • How (specifically) do you want to improve the code?

    By reducing the operations of the code

The code is in Starter Character

run = game:GetService("RunService")
Prison = workspace.Region3:WaitForChild("Prison")
Head = script.Parent:WaitForChild("Head")
run.RenderStepped:Connect(function()
	if Head.Position.X < Prison.Position.X - Prison.Size.X / 2 and Head.Position.X > Prison.Position.X + Prison.Size.X / 2 then
		if Head.Position.Y < Prison.Position.Y - Prison.Size.Y / 2 and Head.Position.Y > Prison.Position.Y + Prison.Size.Y / 2 then
			if Head.Position.Z < Prison.Position.Z - Prison.Size.Z / 2 and Head.Position.Z > Prison.Position.Z + Prison.Size.Z / 2 then
				--Bruhmongus
                print("I'VE GOTTEN OFF DA PRISON")
			end
		end
	end
end)
local Run = game:GetService("RunService")
local Prison = workspace.Region3:WaitForChild("Prison")
local Head = script.Parent:WaitForChild("Head")

function CheckRegion(Axis)
    if Head.Position[Axis] < Prison.Position[Axis] - Prison.Size[Axis] / 2 and Head.Position[Axis] > Prison.Position[Axis] + Prison.Size[Axis] / 2 then
        return true
    else
        return false
    end
end

Run.RenderStepped:Connect(function()
    if CheckRegion("X") and CheckRegion("Y") and CheckRegion("Z") then
        --Bruhmongus
        print("I'VE GOTTEN OFF DA PRISON")
    end
end)

not sure if this is what you wanted, but I hope this helps

1 Like

oh thx so much, I will use this, But if I put its as a solution, other people can help me with other optimizations or not?

anybody is still allowed to come help, regardless if a solution exists on the post or not

1 Like

Another good optimisation you can get down is to change from RenderStepped to Heartbeat. Generally you should never run code in RenderStepped unless it has something to do with changing the Camera’s CFrame, a part of the character (e.g. its transparency) or something that needs to be calculated before frames render.

Since your code doesn’t meet the aforementioned criteria it should just happen at the best possible time for RunService events which is after physics simulation has been performed, Heartbeat. This would be logical for your use case as well because after physics simulation has occurred for the current frame (player’s position is updated) it’d make sense to check if they’re now still in the zone or not.

2 Likes