Title is pretty obvious, I made a kind of hitbox and whenever a model with a Humanoid goes into my hitbox, the baseplate should change colour.
However this is not the case
As you can see in this clip the baseplate stays red and never turns green, even after I touch one of the dummies.
Here is what the hitbox is meant to look like
Hitbox
Script
local player = game:GetService("Players").LocalPlayer
local Chr = player.Character or player.CharacterAdded:Wait()
local root = Chr:WaitForChild("HumanoidRootPart")
local function checkHit()
local cf = root.CFrame + Vector3.new(0,0,-1.5)
local size = root.Size + Vector3.new(0, 0, 20)
local PlayerHitBox = workspace:GetPartBoundsInBox(cf, size)
for i,part in pairs(PlayerHitBox) do
if part.Parent:FindFirstChildWhichIsA("Humanoid") and not Chr then
workspace.Baseplate.Color = Color3.new(0.423529, 1, 0.384314)
else
workspace.Baseplate.Color = Color3.new(1, 0, 0.0156863)
end
end
end
game:GetService("RunService").Stepped:Connect(checkHit)
Edit: I added the not Chr because I dont want the hitbox to interfere in case it touches yourself
Any help would be appreciated, thanks
Are you trying to check if part
belongs to Chr
? not Chr
just means the inverse of Chr
, which is truthy because Chr is not nil
or false
. So not Chr
is always false
, so the if
block never runs only the else
block.
Did you mean if part.Parent:FindFirstChildWhichIsA("Humanoid") and not part:IsDescendantOf(Chr) then
?
Another thing, even if a valid part is found during the for loop, what happens if there are more parts in the hit box? On the second time around the loop it might overwrite the color that you set on a previous loop, which is probably not what you want. Seems like you want to check if any of the parts are valid, and then set the color based on that. Try
local otherCharacterTouching = false
for _, hitPart in ipairs(PlayerHitBox) do
--Use "early continue" instead of nested if statements or if statements with complicated conditions
if not hitPart.Parent:FindFirstChildWhichIsA("Humanoid") then continue end
if hitPart:IsDescendantOf(Chr) then continue end
otherCharacterTouching = true
break --This is optional, just a slight optimization and also makes it clearer to the reader what we're trying to do. Omitting it won't break anything since the loop can never set the variable back to false.
end
if otherCharacterTouching then
baseplate.Color = COLOR_1
else
baseplate.Color = COLOR_2
end