Model failing to replicate on player's avatar

So, I am trying to make it so that if you meet certain requirements, it equips an avatar to your player. It works fine if you do “local g = game.ServerStorage.Medals.medalactivity.Chest:clone()”

However I want to make it easier to add new medals by just having it where the system will determine which medal to clone and define g from if statements (possibly a table, in the future.)

This error appears and is really giving me trouble making this new system. If anybody could help, it’d be greatly appreciated. Thanks!

local Players = game:GetService("Players")



function onPlayerSpawned(player)
	player.CharacterAdded:connect(function(char)
		
		if player.Name == "Submiq" then
			local medal =  game.ServerStorage.Medals.medalactivity.Chest
		elseif player.Name == "BinarySparrow" then
			local medal = game.ServerStorage.Medals.medalservice.Chest
		end



if char:findFirstChild("Humanoid") ~= nil and char:findFirstChild("Chest") == nil then

	local g = medal:clone()
	g.Parent = char
	local C = g:GetChildren()
	for i=1, #C do
		if C[i].className == "Part" or C[i].className == "UnionOperation" or C[i].className == "MeshPart" then
			local W = Instance.new("Weld")
			W.Part0 = g.Middle
			W.Part1 = C[i]
			local CJ = CFrame.new(g.Middle.Position)
			local C0 = g.Middle.CFrame:inverse()*CJ
			local C1 = C[i].CFrame:inverse()*CJ
			W.C0 = C0
			W.C1 = C1
			W.Parent = g.Middle
		end
		local Y = Instance.new("Weld")
		Y.Part0 = char.Torso
		Y.Part1 = g.Middle
		Y.C0 = CFrame.new(0, 0, 0)
		Y.Parent = Y.Part0
	end

	local h = g:GetChildren()
	for i = 1, # h do
		if h[i].className == "Part" or h[i].className == "UnionOperation" then
			h[i].Anchored = false
			h[i].CanCollide = false
		end
	end
end

end)
end
game.Players.PlayerAdded:connect(function(player)
	onPlayerSpawned(player)
end)

That’s because medal is nil. It is defined in the script but it’s not in the same scope as when you cloned it.

I recommend creating the variable before you define medal in a separate scope:

if player.Name == "Submiq" then
    local medal = game.ServerStorage.Medals.medalactivity.Chest
elseif player.Name == "BinarySparrow" then
    local medal = game.ServerStorage.Medals.medalservice.Chest
end

--// To

local medal
if player.Name == "Submiq" then
    medal = game.ServerStorage.Medals.medalactivity.Chest
elseif player.Name == "BinarySparrow" then
    medal = game.ServerStorage.Medals.medalservice.Chest
end

You’re a life saver, thank you!

Do you think this might break the script if a player does not meet said requirements for the medal? (In this instance, they are not one of the player’s names.)

Then simply just do a check if the variable is nil or not, or set a default value.

1 Like