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 5 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:

01script.Parent.Touched:connect(function(hit)
02    script.Parent.TouchEnded:Connect(function(hit2)
03     local ab = hit.Parent
04    local cd = hit.Parent.Momo
05   if ab and cd then
06 
07print("Stahp!!!")
08script.Parent.Parent.Parent.Chassis.stop.Value = true
09script.Disabled = true
10wait(2)
11 
12 
13if hit2.Parent.Momo then
14    script.Parent.Parent.Parent.Chassis.stop.Value = false
15    print("Go.")
View all 23 lines...

2 answers

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

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

1if 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:

01script.Parent.Touched:connect(function(hit)
02if hit.Parent:FindFirstChild('Momo') then
03 
04    script.Parent.TouchEnded:Connect(function(hit2)
05     local ab = hit.Parent
06    local cd = hit.Parent.Momo
07   if ab and cd then
08 
09print("Stahp!!!")
10script.Parent.Parent.Parent.Chassis.stop.Value = true
11script.Disabled = true
12wait(2)
13 
14 
15if hit2.Parent.Momo then
View all 25 lines...
0
That worked, thanks! MirrorI 5 — 5y
Ad
Log in to vote
0
Answered by 5 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