Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How can I make this script not give error each time it doesn't detect a specific part in model?

Asked by 4 years ago

So I'm making a self driving car which I want to stop when it touches a player's car, the script works but when it touches a model that's not a player's car it drops like 20 errors and lags for a bit. The error is: "Momo is not a valid member of Model"

And here's the code:

script.Parent.Touched:connect(function(hit)
    script.Parent.TouchEnded:Connect(function(hit2)
     local ab = hit.Parent
    local cd = hit.Parent.Momo
   if ab and cd then

print("Stahp!!!")
script.Parent.Parent.Parent.Chassis.stop.Value = true
script.Disabled = true
wait(2)


if hit2.Parent.Momo then
    script.Parent.Parent.Parent.Chassis.stop.Value = false
    print("Go.")
    script.Disabled = false
    wait(2)

end
end

    end)
end)

2 answers

Log in to vote
4
Answered by
BuDeep 214 Moderation Voter
4 years ago

At the beginning of the Touch statement, I would add an if statement that says:

if hit.Parent:FindFirstChild('Momo') then

This way the function won't continue unless it finds that Momo is a valid child of hit.Parent.

Here's the full script with it added in:

script.Parent.Touched:connect(function(hit)
if hit.Parent:FindFirstChild('Momo') then

    script.Parent.TouchEnded:Connect(function(hit2)
     local ab = hit.Parent
    local cd = hit.Parent.Momo
   if ab and cd then

print("Stahp!!!")
script.Parent.Parent.Parent.Chassis.stop.Value = true
script.Disabled = true
wait(2)


if hit2.Parent.Momo then
    script.Parent.Parent.Parent.Chassis.stop.Value = false
    print("Go.")
    script.Disabled = false
    wait(2)

end
end
end
    end)
end)
0
That worked, thanks! MirrorI 5 — 4y
Ad
Log in to vote
0
Answered by 4 years ago

Alright so I had a similar issue with a event I had where every time I hit an button to trigger an event, it would say that something is not in that model. Basically, what they suggested to me is make it so it checks to see if the part is actually the part that is needed. Meaning, have it so it checks for the parts it NEEDS then NIL everything else. I'm fairly new to scripting so this may not work but I figured i'd give it a shot and help ya out.

Answer this question