Team Changer on Touch

Ok so, is really simple.

I need a part that when gets touched switches team from “Waiting” to "Playing

Issue: The Code seems to work but i still get an error when playing


part = script.Parent
game.Players:GetPlayerFromCharacter(h.Parent).Team = game.Teams.Playing


It’s fine that is working but i would like to remove those errors that can cause more problems in the future


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. :thinking:

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.


part = script.Parent
	if TouchedObject.Parent:FindFirstChild("Humanoid") then
		game.Players:GetPlayerFromCharacter(TouchedObject.Parent).Team = game.Teams.Playing


  • 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.


Thanks both for the fix! for some reason the second one seems not working but the first does, thanks anyway :smiley:

1 Like

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.