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

Problem with moving a tool from Workspace to Backpack?

Asked by 7 years ago

I have a gun model that works fine, I added a Click detector and a script to make it so when I click the gun it goes from the workspace to the Backpack, when I clicked on the gun in output it printed Glock is not a valid member of Workspace even though as it I read that I saw the gun in workspace, and yes the gun is named exactly Glock,

Below is output yelling at me whilst clicking gun

https://gyazo.com/f67132c50fad4f24ba89e43ac5bfdb73

Below is the Glock in workspace

https://gyazo.com/f67132c50fad4f24ba89e43ac5bfdb73

local clickDetector = script.Parent

 local function onMouseClick(player)

wait(0.7)
game.Workspace.Glock = player.Backpack

end
clickDetector.MouseClick:connect(onMouseClick)

It is a short script and I may not be fully done with it, as the output said the problem is line 6 as Glock isn't in workspace even though it is, so my question is, is Roblox trying to pull Paranormal Investigations or am I missing something very obvious?

1
You forgot `.Parent` on line 6, after `game.Workspace.Glock`. Also, you should be checking if it exists before trying to parent it anyway. Pyrondon 2089 — 7y

1 answer

Log in to vote
1
Answered by
Async_io 908 Moderation Voter
7 years ago

I would recommend removing the wait and using a FindFirstChild, or possibly even a WaitForChild.

FINDFIRSTCHILD

FindFirstChild will look for the first child with the name provided. If the child does not exist, then it will return either nil, or if you're using an if statement, false.

An example if statement withFindFirstChild would be

local normalPart = game.Workspace:FindFirstChild('NormalPart')
if normalPart then
    print('Normal part exists!')
else 
    print('Normal part does not exist.')
end
--or you could use--
if game.Workspace:FindFirstChild('NormalPart') then
    print('Normal part exists!')
else
    print('Normal part does not exist.')
end

WAITFORCHILD

WaitForChild will wait until the child is not nil.

An example would be

local normalPart = game.Workspace:WaitForChild('NormalPart')

THE ERROR

When you're trying to give a tool to a player, you need to reassign the tool's parent. You can do this by simply using tool.Parent = player.Character, assuming that you have the defined variables.

local clickDetector = script.Parent

 local function onMouseClick(player)

if game.Workspace:FindFirstChild('Glock') then --Double checking to make sure it's valid. 
    game.Workspace.Glock.Parent = player.Backpack --Putting it into the player's backpack.
end

end
clickDetector.MouseClick:connect(onMouseClick)

Ad

Answer this question