Function won't work : Workspace.MovePartScript:20: attempt to index nil with 'Completed'

I made this function that could allow me to input a part, model, or folder as the first input, a TweenInfo as the second input, a Vector3 as the third input, and true or false as the fourth input. However, when the fourth input is true, I get the error Workspace.MovePartScript:20: attempt to index nil with 'Completed'

function MovePart(part, info, translation, waituntildone)
	local Tween
	
	if part:IsA("BasePart") then
		Tween = TS:Create(part, info, {Position = part.Position + translation})
		Tween:Play()
	end
	if part:IsA("Model") then
		for i, v in pairs(part:GetDescendants()) do
			if v:IsA("BasePart") then
				Tween = TS:Create(v, info, {Position = v.Position + translation})
				Tween:Play()
			end
		end
	end

	if waituntildone == true then
		Tween.Completed:Wait()
	end
end

Does anyone know how I can fix this?

At the beginning of the function, you are initialising the variable Tween with no value, which will default to nil. This is not necessarily the issue, however, the logic of your code would be where you can fix this error.

Let’s say that you provide the parameter part with a folder, as stated in your post description. The first two if statements would not go through, because a folder is neither a BasePart or a Model. Therefore, Tween would remain as nil. So when the program reaches Tween.Completed:Wait(), it will return an error as Tween is still nil.

I would recommend that you amend your code to include a check for anything that is not a BasePart or Model.

if not part:IsA("BasePart") or not part:IsA("Model") then return end
You can change this if statement to have multiple lines, but this is a concise way to do it.

1 Like

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