I'm trying to make the brick change color but I keep getting a error from line 7. Error:
Workspace.Script:7: attempt to index local 'hit' (a nil value)
while wait()do local Ray = Ray.new(game.Workspace.Part1.Position, game.Workspace.Part1.CFrame.lookVector.unit*10) -- 1000 is normally used, but you can reduce as you see fit. Not multiplying this is only 1 stud from Part1's *center* towards its lookVector. local hit = Workspace:FindPartOnRay(Ray) if hit:IsA("Part") then game.Workspace.Part1.BrickColor = BrickColor.new("Bright green") else game.Workspace.Part1.BrickColor = BrickColor.new("Bright red") end end
Why and how would I fix it?
I do not have a solution to your problem, though I do know the reason that it does not work.
Your problem is that you are trying to check if hit
is a part before it actually exists. That is due to the while
loop. Basically, you are constantly checking if hit
is a part, before the ray actually hits anything.
Now, I have a theory as to how you could solve your problem, although I am not sure how it would work. If rays can fire functions when they touch something, then you could have it run a function changing the BrickColor of the hit object if it is a part every time it hits something. I am not sure how that would work, as I am no expert with rays, but I am sure it is possible.
What Goulstem was getting at:
while wait()do local Ray = Ray.new(game.Workspace.Part1.Position, game.Workspace.Part1.CFrame.lookVector.unit*10) -- 1000 is normally used, but you can reduce as you see fit. Not multiplying this is only 1 stud from Part1's *center* towards its lookVector. local hit = Workspace:FindPartOnRay(Ray) repeat wait() until hit~=nil --Waits until hit is not nil. if hit:IsA("Part") then game.Workspace.Part1.BrickColor = BrickColor.new("Bright green") else game.Workspace.Part1.BrickColor = BrickColor.new("Bright red") end end
Hope I helped!