Why does this script work sometimes?

I’m having difficulty understanding why this script only works sometimes, and other times it doesn’t. It’s supposed to change the player’s team as well as their clothes but it doesn’t work.
It’s a normal script in ServerScriptService.

local ScientistClass = game.ReplicatedStorage.ScientistClass
local Teams = game:GetService("Teams")
local players = game.Players
ScientistClass.Event:Connect(function(player)
		print('working')
		player.CharacterAdded:Connect(function (character)
		character:WaitForChild("Shirt"):Destroy()
		character:WaitForChild("Pants"):Destroy()
		local Shirts = Instance.new("Shirt",character)
		local Pants = Instance.new("Pants", character)
		player.Team = Teams.Scientist
		Shirts.ShirtTemplate = "http://www.roblox.com/asset/?id=519722780"
		Pants.PantsTemplate = "http://www.roblox.com/asset/?id=519722963"
		player.Character.HumanoidRootPart.CFrame = CFrame.new(25.57, 15.547, 46.05)
		end)
end)

I’m not sure why changing it to

local ScientistClass = game.ReplicatedStorage.ScientistClass
local Teams = game:GetService("Teams")
local players = game.Players
ScientistClass.Event:Connect(function(player)
		player.Character:WaitForChild("Shirt"):Destroy()
		player.Character:WaitForChild("Pants"):Destroy()
		local Shirts = Instance.new("Shirt",player.Character)
		local Pants = Instance.new("Pants", player.Character)
		player.Team = Teams.Scientist
		Shirts.ShirtTemplate = "http://www.roblox.com/asset/?id=519722780"
		Pants.PantsTemplate = "http://www.roblox.com/asset/?id=519722963"
		player.Character.HumanoidRootPart.CFrame = CFrame.new(25.57, 15.547, 46.05)
end)

worked because earlier it didn’t

1 Like

Hey! First of all a few things:

Change “game.Players” to: game:GetService(“Players”)

Second, to connect a remote event, say this:

ScientistClass.Event.OnServerEvent:Connect(function(player)

Also, you use asset IDs, and there’s a change that sometimes they don’t load.

I recommend converting your shirts and pants templates with this plugin: https://www.roblox.com/library/2849322379/Imiji-convert-image-IDs

I hope this helped you out!

1 Like

Why write code you won’t use?

When creating a new instance try to not use the second argument(assigning the instance a parent).

This is a case of semantic error, hence the undesired result.