Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

My function seems not to return it's object, turns out nil, what's the problem?

Ok, first i call my function to return an object so i can clone it:

local newActualPad = closeByCheck(currentPly):Clone()

closeByCheck has to return me an object so i can clone it

local closeByCheck = function(ply)
	local part 
	print("closeByCheck")
	local signal
	signal = ply:FindFirstChild("Right Leg").Touched:connect(function(otherPart)
	print("Touched")
	print(otherPart.Parent)
	if otherPart.Parent == game.Workspace.Grid then
		print("Part is grid")
		if (ply.HumanoidRootPart.Position - otherPart.Position).magnitude < startRange then
			print("Part is close")
			part = otherPart
			print(part.Name)
		end
	end
	signal:disconnect()
	
end)
       return part
end

When i run it, closeByCheck returns me nothing, and when the script is gonna clone, error, attempt to index a 'nil'

1 comment

1

It's most probably something with the 'if' at line 10, because if the if goes false then the part never gets defined, so it would return nil

1 answer

✓ Accepted answer

A connection doesn't take time. Your code executes like this:

  1. part = nil
  2. start listening for a touched
  3. return part

Since part (2.) is done immediately, your closeByCheck might as well be return nil.


You could wait until part is not nil, for example:

	repeat
		wait()
	until part
	return part

Though I'm not sure if a design that waits for a contact makes sense, since it could be a very long time before anything touches this.

This discussion is preserved as it was. New answers, comments, and votes are closed.