Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do you remove a viewmodel after it's unequipped?

Asked by 3 years ago

I am trying to remove the viewmodel after my tool is unequipped but this happens.

"Model:SetPrimaryPartCFrame() failed because no PrimaryPart has been set, or the PrimaryPart no longer exists. Please set Model.PrimaryPart before using this."

After it's destroyed it say's the error. I tried to use clone but it doesn't fix it.


local cam = workspace.CurrentCamera

local player = game.Players.LocalPlayer

local viewmodel = game.ReplicatedStorage.viewmodel:Clone()

viewmodel.Parent = cam

local character = player.Character

viewmodel.PrimaryPart = viewmodel.HumanoidRootPart

local runservice = game:GetService("RunService")

local gunTool = nil

local function setcam()

while guntool and runservice.RenderStepped:Wait() do

    viewmodel:SetPrimaryPartCFrame(cam.CFrame*CFrame.new(0.5, -0.5, -1))
end

end

character.ChildAdded:Connect(function(child)

if child:IsA("Tool") and child.Name == "FastCastGun" then

    guntool = child
    setcam()
          if viewmodel.Parent == game:GetService("ReplicatedStorage") then
        viewmodel:Clone() -- I tried to use this to fix but still it says the error
        viewmodel.Parent = cam
    end
end

end)

character.ChildRemoved:Connect(function(child)

if child and child == guntool then

    guntool = nil --maybe here's the problem
        viewmodel:Destroy() -- or this 
end

end)

1 answer

Log in to vote
0
Answered by 3 years ago

Looking at this function:

local function setcam()
    while guntool and runservice.RenderStepped:Wait() do
        viewmodel:SetPrimaryPartCFrame(cam.CFrame*CFrame.new(0.5, -0.5, -1))
    end
end

The while loop is still running even after the viewmodel is destroyed. A simple fix would be to add the viewmodel variable into the while loop's condition. I believe this should work:

local function setcam()
    while guntool and viewmodel and runservice.RenderStepped:Wait() do
        viewmodel:SetPrimaryPartCFrame(cam.CFrame*CFrame.new(0.5, -0.5, -1))
    end
end
0
It still doesn't work. It still say's the error RichDiggerW189 2 — 3y
0
Try setting the viewmodel variable to nil after the line "viewmodel:Destroy()" efficacies 180 — 3y
Ad

Answer this question