Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

'string expected, got instance'. How to fix?

Asked by 3 years ago

Hello. I am trying to make a player title script but it keeps on outputting the error 'string expected, got instance'.

Here is my code:

local Players = game:GetService("Players")

local function title(plr)
    if plr.Name == 'PufferfishDev' then
        wait(1)
        local ws = game:GetService('Workspace')
        local rs = game:GetService('ReplicatedStorage')
        local titleClone = rs.devTitle:Clone()
        titleClone.Parent = ws[plr].Head
    end
end

Players.PlayerAdded:Connect(title)
0
I forgot to say, the error is occuring on Line 9 PufferfishDev 49 — 3y

1 answer

Log in to vote
0
Answered by
imKirda 4491 Moderation Voter Community Moderator
3 years ago

On line 9 you are indexing ws with player, which is Instance, indexing Instances in Roblox must be done with strings, you can fix that by putting plr.Name there

titleClone.Parent = ws[plr.Name].Head

However Player Instance has property called Character which refers to his current character, you can use it instead of looking for him inside of workspace

titleClone.Parent = plr.Character.Head

Your code, however, has few issues, first of all, wait(1) is not going to guarantee that the character is loaded, second, you only give title to yourself when you join, that is once, if you reset character your title will be lost, for that you can use CharacterAdded event which fires when your character loads, you can connect it to a function when the player joins

local Players = game:GetService("Players")
local ws = game:GetService('Workspace')
local rs = game:GetService('ReplicatedStorage')

local function title(plr)
    if plr.Name == "PufferfishDev" then

        local function OnCharacterAdded(Character)
            local titleClone = rs.devTitle:Clone()

            titleClone.Parent = Character:WaitForChild("Head")
        end

        plr.CharacterAdded:Connect(OnCharacterAdded)
    end
end

Players.PlayerAdded:Connect(title)

This will create title for you every time you spawn, also see i used WaitForChild, it yields until instance with name is found inside of the caller, the Character in this case. This is because when your character spawns, parts are not 100% replicated and indexing them will result in an error.

Consider storing variables of services in main scope if you are going to use them multiple times, if only once in the title function, it's okay.


CharacterAdded

WaitForChild

0
Thanks so much!!!! PufferfishDev 49 — 3y
Ad

Answer this question