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

Why is the script saying its a nil value but Roblox is saying it isnt?

local player
local distance

getplayer()

while wait(1) do
	if player ~= nil then
		print("Player is nil.")
	else
		getplayer()
		wait()
		distance = (script.Parent.Torso.Position - player.Torso.Position).magnitude
		checkdistance()
	end
end

function checkdistance()
	if distance <= 15 then
		print("Humanoid got Near")
	end
end


function getplayer()
	for _, inst in pairs(workspace:GetChildren()) do
		if game.Players:GetPlayerFromCharacter(inst) then
			player = inst
			print(inst)
			break
		end
	end
end

SOMEHOW IN THE OUTPUT IM GETTING A ATTEMPT TO CALL A NIL VALUE IN THE WHILE LOOP, WHEN I CLICK IT IT DIRECTS ME TO THE LINE WHERE IT SAYS else getplayer()

BUT ISN'T IT IMPOSSIBLE FOR THE FUNCTION BE CALLED BECAUSE IT WONT BE CALLED UNLESS THE PLAYER IS A NIL VALUE??

1 answer

Problem:

You are using a

if player ~= nil then

which means if the player is not equal to nil then print the player is nil, so if the player was nil, it would skip the print and try to run the else potion of the program, which fails, because it is nil.

Solution:

script:

local player
local distance
function checkdistance()
    if distance <= 15 then
        print("Humanoid got Near")
    end
end


function getplayer()
    for _, inst in pairs(workspace:GetChildren()) do
        if game.Players:GetPlayerFromCharacter(inst) then
            player = inst
            print(inst)
            break
        end
    end
end

getplayer()

while wait(1) do
    if player == nil then -- changed here
        print("Player is nil.")
    else
        getplayer()
        wait()
        distance = (script.Parent.Torso.Position - player.Torso.Position).magnitude
        checkdistance()
    end
end


The functions also have to be declared before they can be used.

1 comment

0

I wanna upvote this answer but I can't!

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