Attempt to Index Function

So I have an issue with an error saying "Attempt to index function with RoleCharacter. I’m not sure what’s causing it but here’s the code:

remotes:WaitForChild(“ChooseRole”).OnServerEvent:Connect(function(plr, role)

	if plr and not plr.Character then
		if roles:FindFirstChild(role) then
			
			local newCharacter = roles[role].RoleCharacter:FindFirstChildOfClass("Model"):Clone()
			newCharacter.Name = plr.DisplayName
			plr.Character = newCharacter
			newCharacter.Parent = workspace
			
			for _, tool in pairs(roles[role].Tools:GetChildren()) do
				tool:Clone().Parent = plr.Backpack
			end
		end
	end
end)

The issue is coming from this line:

local newCharacter = roles[role].RoleCharacter:FindFirstChildOfClass("Model"):Clone()

Any help is appreciated! :slight_smile:

Likely means that roles[role].RoleCharacter isn’t a part or model or that there isnt a model inside RoleCharacter

The error “Attempt to index function with RoleCharacter” occurs because the variable “roles[role]” is a function, not a table. To fix the error, you need to make sure that “roles[role]” is a table with the “RoleCharacter” property.

You can modify your code to check if “roles[role]” is a table with the “RoleCharacter” property before trying to clone it. Here’s an updated version of the code:

remotes:WaitForChild("ChooseRole").OnServerEvent:Connect(function(plr, role) if plr and not plr.Character then local roleData = roles[role] if roleData and roleData.RoleCharacter then local characterModel = roleData.RoleCharacter:FindFirstChildOfClass("Model") if characterModel then local newCharacter = characterModel:Clone() newCharacter.Name = plr.DisplayName plr.Character = newCharacter newCharacter.Parent = workspace

			for _, tool in pairs(roleData.Tools:GetChildren()) do
				tool:Clone().Parent = plr.Backpack
			end
		end
	end
end

end)

This code checks if “roles[role]” exists and has the “RoleCharacter” property, and then checks if the “Model” inside “RoleCharacter” exists before cloning it.

The variable role is a function. The error occurred due the function being indexed (.RoleCharacter).

Make it so that roles table do not contain something that cannot be indexed with RoleCharacter or add an if-statememt to check if role is a function or not to skip indexing functions.

It would be nice if we can see what happens outside the code you have given us to roles table

1 Like