Attempt to index nil with 'Clone' for a buy button

the line of code giving the item purchased by the player via the buy button gives me that error :attempt to index nil with ‘Clone’ and I don’t know why.

script :

local player = game.Players.LocalPlayer
local backpack = player.Backpack




price = 20




tool = game.ServerStorage:FindFirstChild("Pilule")

script.Parent.MouseButton1Click:Connect(function()
	if player.leaderstats.Dollars.Value >= 20 then
		player.leaderstats.Dollars.Value -= price
		local b = tool:Clone()
		b.Parent = player.Backpack
	end
end)


You cant access ServerStorage from local scripts, Parent the tool to ReplicatedStorage and clone it from there

1 Like

it works I can buy and collect the item. Strangely enough, however, any item I buy with a script doesn’t work. For example, a medical kit that restores life by clicking when you equip it doesn’t work once it’s bought and in hand, whereas if I put my tool in StarterPack, the medical kit works. As if all scripts were deactivated from purchased items.

1.you cant access serverstorage from client
2.notice you change the player stats on client meaning it wont replicate to server and can be problematic, use a remote event to handle the purchase on the server side.

1 Like

As @Maxime_360 and @Valkyrop mentioned, you are typing the code in a LocalScript which means the code is running client-side. The client cannot access items stored in the ServerStorage, that is why it returns nil when referencing the tool. You should consider using a RemoteEvent to add it from the server.

An example of how you could do this using a RemoteEvent

local script - in a Gui

script.Parent.MouseButton1Click:Connect(function()
	game.ReplicatedStorage.ToolEvents.HealthDrink:FireServer()
end)

script - in ServerScriptService

game.ReplicatedStorage.ToolEvents.HealthDrinkEvent.OnServerEvent:Connect(function(player)
	if player.leaderstats.Coins.Value >= 6 then
		player.leaderstats.Coins.Value = player.leaderstats.Coins.Value - 6
		game.ServerStorage.Tools.HealthDrink:Clone().Parent = player.Backpack
	end
end)

1
2

The script in ServerScriptService could have many tools in the same script.
All one right after eachother. Each with their own event in ReplicatedStorage.

1 Like

it works thank you very much !

can you take a look at this SCRIPTING How do i stop animation in gun tool after playing - #4 by BIGmartha27

jay can you take a look at this SCRIPTING How do i stop animation in gun tool after playing - #4 by BIGmartha27

Odd you ask that … I’m going to work on something like that today.
I’ll get back to you in that post …

i figured it out dude , you had to make an animation track

i could give u the script if u wanted dude

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