How to make if statement to check if plr.Name == Occupant.Name

How can I check if the occupant in the DriverSeat is = plr.Name?

if plr.Name == DriveSeat.Occupant.Name then

error
attempt to index nil with ‘Name’

That’s because Occupant is a Humanoid object. You need to find the character from the occupant first, then get the player from the character, then index it’s name. :slight_smile:

Example:

local occupantChar = DriveSeat.Occupant.Parent
local occupantPlayer = game.Players:GetPlayerFromCharacter(occupantChar)

if plr.UserId == occupantPlayer.UserId

EDIT: It might not be needed, but you should use UserId for player object comparisons unless the use-case differs, since UserId’s are constant/unique to each player, they never change, even if the player changes their username. :slight_smile:

See what the occupant property return is here on the documentation for seat.

3 Likes
if plr.Name == DriveSeat.Occupant.Parent.Name then

mathews answer is better mine is more of slapping a bandage on it

1 Like

This way definitely suffices to be honest, the only reason UserId would be preferred over a name is for long-term use cases where names could change, data saving being one of them.

1 Like

the only concern i would have is idk if the workspace character is named after display name or real name and if the same goes for the player name

SOOOO use userid instead

OR compare instances player.character = driveseat.occupant.parent

1 Like

Thanks for they reply!
I keep getting this error attempt to index nil with ‘UserId’
on this line

if plr.UserId == occupantPlayer.UserId then

Sadly this didn’t work
error
attempt to index nil with ‘Parent’

Next time you ask for help, please share more of your code, and additional details, ex.: if it’s a localscript, or a server script.

Anyways, you could do the following (Make sure plr is an actual Player):

DriveSeat:GetPropertyChangedSignal("Occupant"):Connect(function(humanoid)
    if humanoid ~= nil then
        if plr.Name == humanoid.Parent.Name then
            -- do whatever you want
        end
    end
end)
1 Like

my bad its a server script in serverscriptservice

this is the code so far I didn’t get far.

local finder = workspace:WaitForChild(plr.Name.."'s Car")
finder.DriveSeat:GetPropertyChangedSignal("Occupant"):Connect(function(humanoid)
			print(humanoid)
			print(plr)
			if humanoid ~= nil then
			
				if plr.Name == humanoid.Parent.Name then
print("Seat")

Humanoid keeps printing as nil when in driveseat. plr prints my username. This time no errors tho

okay, instead of using humanoid, you can do

finder.DriveSeat:GetPropertyChangedSignal("Occupant"):Connect(function()
	if finder.DriveSeat.Occupant ~= nil then
		if plr.Name == finder.DriveSeat.Occupant.Parent.Name then
			print("Seat")
		end
	end
end)
1 Like

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