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

Why won't the following code work? Issue with GetPlayerFromCharacter

Script that is a child of a part that when touched, you change into an outfit

function onTouched(part)
	local character = part.Parent
	local players = game:GetService("Players")
	local player = players:GetPlayerFromCharacter(part.Parent)
	local shirt = character:FindFirstChildOfClass("Shirt")
	local pants = character:FindFirstChildOfClass("Pants")
    	if not shirt then 
    			shirt = Instance.new("Shirt", character)
    	end 
    	if not pants then 
    			pants = Instance.new("Pants", character)
     	end
		if player.Team == "Red" then
		shirt.ShirtTemplate = "rbxassetid://136056214"
		pants.PantsTemplate = "rbxassetid://136056214"
		    	end
		if player.Team == "Blue" then
		shirt.ShirtTemplate = "rbxassetid://136056667"
		pants.PantsTemplate = "rbxassetid://136056667"
		    	end
	end

script.Parent.Touched:connect(onTouched)

3 comments

0

I will test it to check for errors BHreghdsifodsiu

0

ok

0

crap he already did it

1 answer

✓ Accepted answer

You should always check to see if player exists because sometimes another part may touch the part the event's connected to, and GetPlayerFromCharacter will return nil.

Also, you should note that using Instance.new's 2nd parameter is not advised, because of performance issues

function onTouched(part)
    local character = part.Parent
    local players = game:GetService("Players")
    local player = players:GetPlayerFromCharacter(part.Parent)
    local shirt = character:FindFirstChildOfClass("Shirt")
    local pants = character:FindFirstChildOfClass("Pants")
    if player then
        if not shirt then 
                shirt = Instance.new("Shirt")
                shirt.Parent = character
        end 
        if not pants then 
                pants = Instance.new("Pants")
                pants.Parent = character
        end
        if player.Team == "Red" then
            shirt.ShirtTemplate = "rbxassetid://136056214"
            pants.PantsTemplate = "rbxassetid://136056214"
        end
        if player.Team == "Blue" then
            shirt.ShirtTemplate = "rbxassetid://136056667"
            pants.PantsTemplate = "rbxassetid://136056667"
        end
    end
end

script.Parent.Touched:Connect(onTouched)

1 comment

0

thx

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