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!
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