Script runs only when cast.Instance changes

I need my script to run ONLY when the cast.Instance changes, including when it doesn’t exist anymore.
I’ve tried this, but it errors since when the cast is nil, the cast.Instance doesn’t even exist.

local mouseLocation = UserInputService:GetMouseLocation()
local unitRay = camera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y)
local cast = workspace:Raycast(unitRay.Origin, unitRay.Direction * 1000, CastParams)
	
print(cast)
	
if cast.Instance ~= previousCastInstance then
	
	previousCastInstance = cast.Instance 
	
	print("run script")

end

This script is run every heartbeat by the way. Thanks!

To avoid the error of cast being nil, you can add to the if statement.

if cast and cast.Instance ~= previousCastInstance then

end

Your code should stop erroring with this, and might solve the other issue as well.

but what about it running when the cast goes from a part to nil?
This won’t detect that since it only runs if the cast isn’t nil

You could just assign previousCastInstance outside of the if statement. Or, add an elseif/else.

if cast and cast.Instance ~= previousCastInstance then
end

previousCastInstance = cast
if cast and cast.Instance ~= previousCastInstance then
    --your code here

    previousCastInstance = cast.Instance :: Instance
elseif not cast then
    previousCastInstance = nil :: nil
end

What are the " :: " ? Thanks!

30 chаracters

That just indicates type casting - it’s not necessary. For example, if I initialised a variable as a string:

local var:string = "hi"

and then changed it to a number, I would use double colons to indicate that. It just lets you know the type of the variable has changed.

var = 3 :: number

Like I said, it’s not necessary; at least not in Luau, but in some languages it is. Just preference for me sometimes.


Here’s what the code above returns if that helps:

So previousCastInstance is now assigning, what is the issue?

Ah, makes sense, it just tells the program which specific class it should define the variable as. Makes sense :smiley:

1 Like

it doesn’t run my code when it changes from a part to nil

Here:


Like, it should run when the cast changes from part to part, and from part to nil

After three hours, this is what I came up with:


It thankfully works. So much trial and error. Ugh

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.