This code works but it's a mess, any tips?

local raft = game.ReplicatedStorage.Raft
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local character = game.Workspace:WaitForChild(player.Name)
local RootPart = character:WaitForChild("HumanoidRootPart")
local Holding = false
local camera = workspace.CurrentCamera
local ClonedItem = {}
local SpawnLocation = {}
local RunService = game:GetService("RunService")
local CurrentMaterial = {}
local CurrentLoop = {}
 
 
script.Parent.Equipped:Connect(function()
    if not Holding then
    Holding = true
    local item = raft:Clone()
    ClonedItem = item
    ClonedItem.Parent = game.Workspace.BuildRaft
    ClonedItem.Name = player.Name
    mouse.TargetFilter = item
    local ray = Ray.new(ClonedItem.PrimaryPart.CFrame.Position, Vector3.new(0,-5,0))
    local ignore = {}
   
    for _, parts in pairs(raft:GetChildren()) do
        if parts:IsA("BasePart") then
            ignore[#ignore + 1] = parts
        end
    end
   
    local Part, Position, SurfaceNormal, Material = workspace:FindPartOnRayWithIgnoreList(ray,ignore)
    local step = {}
    step = RunService.Heartbeat:Connect(function()
        if Holding then
           
    local ray = Ray.new(ClonedItem.PrimaryPart.CFrame.Position, Vector3.new(0,-5,0))
    local ignore = ClonedItem
    local Part, Position, SurfaceNormal, Material = workspace:FindPartOnRay(ray,ignore)
        ClonedItem:MoveTo( RootPart.CFrame.Position + (mouse.UnitRay.Direction * 20 ))
       
        if Material == Enum.Material.Water then
            CurrentMaterial = Material
            print("Water")
            for i, v in pairs(ClonedItem:GetChildren()) do
                v.BrickColor = BrickColor.new("Lime green")
                print(v.BrickColor)
                SpawnLocation = ( RootPart.CFrame.Position + (mouse.UnitRay.Direction * 20 ))
            end
        elseif Material ~= Enum.Material.Water then
            CurrentMaterial = Material
            for i, v in pairs(ClonedItem:GetChildren()) do
                v.BrickColor = BrickColor.new("Really red")
            end
       
        CurrentLoop = step
       
        print(tostring(Material))
        elseif not Holding then
            print("Disconnected")
            step:Disconnect()
            end
           
            end
   
        end)
    end
end)
 
 
script.Parent.Unequipped:Connect(function()
    ClonedItem:Destroy()
    Holding = false
end)
 
 
script.Parent.Activated:Connect(function()
   
    game.ReplicatedStorage.BuildRaft:FireServer(SpawnLocation,CurrentMaterial)
    CurrentLoop:Disconnect()
end)
3 Likes

Sorry late reply.
But seems like all is good.
Consider comments between code blocks.

-- like this

I have lost myself on some of my older scripts when i read trough them. :grinning:

4 Likes

Thanks. It needs some work I can break it pretty easily, trial and error I guess, thanks for the reply.

2 Likes