I have had a similar issue before, but it has come up again. I have a Touched event script in workspace to detect when a player touches a certain block then it changes an ObjectValue to that block. There is also a Touch Ended event that sets the block value to nil. Problem: When the player uses a tool, an animation happens and the ObjectValue becomes nil because the player moves. Same thing happens if you Equip/Unequip a tool. Here’s the script:
for i,v in pairs(workspace:GetDescendants()) do
if v.Name == "SugarBlock" then
local touchBlock = v.TouchBlock
touchBlock.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
plr.SugarBlock.Value = v.PrimaryPart
end
end)
touchBlock.TouchEnded:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
plr.SugarBlock.Value = nil
end
end)
end
end
Are there better alternatives to Touched and TouchEnded? (The blocks’ cancollide are set to off).
If you’re using the touch/touchended event to track if a player is in a region, you could use a function to calculate whether a player is inside an area or not. You could also use Region3, however, when I used that it caused really bad performance issues in a game heavily populated with terrain/parts. If you have performance issues too, you can use this to find a player’s region:
function calcRegion(region)
local chrPos = chr.HumanoidRootPart.CFrame.p
local xCoord = chrPos.X
local yCoord = chrPos.Y
local zCoord = chrPos.Z
local regionPos = region.CFrame.p
local regionSize = region.Size
local xMin = regionPos.X - regionSize.X/2
local xMax = regionPos.X + regionSize.X/2
local zMin = regionPos.Z - regionSize.Z/2
local zMax = regionPos.Z + regionSize.Z/2
local yMin = regionPos.Y - regionSize.Y/2
local yMax = regionPos.Y + regionSize.Y/2
if xCoord > xMin and xCoord < xMax and zCoord > zMin and zCoord < zMax and yCoord > yMin
and yCoord < yMax then
if curTouch ~= region then
prevTouch = curTouch
curTouch = region
end
return true
else
return false
end
end
Well the easy way out would be connecting a repeat loop to the touched event that checks the magnitude of you and the block’s range, and If you’re out of the range then the value becomes nil.