Essentially what’s happening here, is that you’re trying to get a player object from the part-which-touched-the-object’s parent, but there’s no guarantee that this actually is anyone’s character.
So what can we do? Well… we know that every character has a Humanoid in it, so why don’t we check if the part’s parent has a Humanoid parented to it?
We can do so by using the method :FindFirstChild() which safely checks if there’s an instance with the provided name parented to something.
Example:
part = script.Parent
part.Touched:Connect(function(TouchedObject)
if TouchedObject.Parent:FindFirstChild("Humanoid") then
print("Switching..")
game.Players:GetPlayerFromCharacter(TouchedObject.Parent).Team = game.Teams.Playing
end
end)
Nitpicks:
Remember to use :Connect, and not :connect with lower-case c, due to it being deprecated and is not supposed to be used for future projects.
You referred to the object which touched the part with the name h. This is something you should try to avoid doing as it’s much better to properly name the variables which you’re working with when coding to prevent confusion. Therefore, I renamed this to TouchedObject which quite obviously refers to the object that touched the part.
Extra: I’m glad that you decided to get help with removing errors from your code. This is good practice and should always be your top priority when programming in general - making sure that your code is error-free.
Should work 100% now! My bad, I rushed through the code and forgot to rename the game.Players:GetPlayerFromCharacter(h.Parent).Team to game.Players:GetPlayerFromCharacter(TouchedObject.Parent).Team when I changed h from TouchedObject in the second line.
However, the fix I provided is good practice and should definitely be used for this.