I'm trying to make a shop pop up when the player touches the shop. What the code is doing is that it goes through every single body part, checks if it has the function :GetTouchingParts(), inserting it into a table, checking if the table contains any object with the name of "ShopHitbox" and setting plrInteractedWithHitbox to true. Why does this not work?
Code:
local char = script.Parent local plr = game.Players:GetPlayerFromCharacter(char) local plrGui = plr.PlayerGui local plrInteractedWithHitbox = false while not plrInteractedWithHitbox do local touchingParts = {} for i, v in pairs(char:GetChildren()) do if pcall(function() local t = v:GetTouchingParts() end) then table.insert(touchingParts, i + 1, v:GetTouchingParts()) end end for i, v in pairs(touchingParts) do if v.Name == 'ShopHitbox' then plrInteractedWithHitbox = true end end if plrInteractedWithHitbox == true then print('test') end wait() end
BasePart:GetTouchingParts() returns a table of objects, not the objects themselves.
To fix this, use another for loop. (replace lines 15-19)
for i, v in pairs(touchingParts) do for _, p in pairs(v) do if p.Name == 'ShopHitbox' then plrInteractedWithHitbox = true break -- Break the loop when ShopHitbox is found. end end if plrInteractedWithHitbox then break -- When plrInteractedWithHitbox is true, break this loop too. end end
Edit 1: Added another break for the touchingParts loop.
Edit 2: Full script with fix as requested (used mobile to add edit after waking up):
local char = script.Parent local plr = game.Players:GetPlayerFromCharacter(char) local plrGui = plr.PlayerGui local plrInteractedWithHitbox = false while not plrInteractedWithHitbox do local touchingParts = {} for i, v in pairs(char:GetChildren()) do if pcall(function() local t = v:GetTouchingParts() end) then table.insert(touchingParts, i + 1, v:GetTouchingParts()) end end for i, v in pairs(touchingParts) do for _, p in pairs(v) do if p.Name == 'ShopHitbox' then plrInteractedWithHitbox = true break -- Break the loop when ShopHitbox is found. end end if plrInteractedWithHitbox then break -- When plrInteractedWithHitbox is true, break this loop too. end end if plrInteractedWithHitbox == true then print('test') end wait() end