For some reason this script only works once

so this script is inside of a brick in the workspace and when i touch it its supposed to send the part flying towards the character and it works, but only once

everytime I try to do it again I get an error code saying "The Parent property of Superball is locked, current parent: NULL, new parent Workspace "

cd = false

local servstor = game:GetService("ServerStorage")

local tweenservice = game:GetService("TweenService")

local superball = servstor.GameplayStorage.Superball:Clone()

local info = TweenInfo.new(1 , Enum.EasingStyle.Linear, Enum.EasingDirection.Out, -1, false)

script.Parent.Touched:Connect(function(plr)
	local newpos = plr.Position

	local tween = tweenservice:Create(superball, info, {Position = newpos})
	
	if cd == false then
		cd = true
		superball.Parent = workspace
		superball.Position = script.Parent.Position + (script.Parent.CFrame.LookVector * 70)
		tween:Play()
		superball.Script.Enabled = true
		wait(1)
		cd = false
	end
end)

I think what’s happening is the superball is getting destroyed after it hits the player. When a part is destroyed its parent is set to nil and it’s marked for trash collection so it isn’t possible to re-parent it to the workspace. The fix would be to clone the superball within the touch handler so you get a new one each time the block is touched.

cd = false

local servstor = game:GetService("ServerStorage")

local tweenservice = game:GetService("TweenService")

local info = TweenInfo.new(1 , Enum.EasingStyle.Linear, Enum.EasingDirection.Out, -1, false)

script.Parent.Touched:Connect(function(plr)
	local newpos = plr.Position

	local tween = tweenservice:Create(superball, info, {Position = newpos})
	
	if cd == false then
		cd = true
		local superball = servstor.GameplayStorage.Superball:Clone()
		superball.Parent = workspace
		superball.Position = script.Parent.Position + (script.Parent.CFrame.LookVector * 70)
		tween:Play()
		superball.Script.Enabled = true
		wait(1)
		cd = false
	end
end)

Does superball.Script call :Destroy() on the superball? Because you are only making a single clone at the beginning of the script.

Consider cloning superball to create a new instance every time the .Touched event is invoked

Additionally, you should set the .Parent property after setting other properties because it is faster due to the way property assignments are executed per script execution cycle.


Edit: I seemed to reply at the same moment as someone else!

Yes, I think this is happening too:

Also, like I noted above, you should set .Position before .Parent since when an instance becomes a descendant of game a lot of heavy code immediately starts running for that instance.

1 Like