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

Am I using the .Character command correctly?

Asked by 6 years ago

I am working on a local script that detects the team a player is on and changes their team if they die.

while true do
    local t1 = game.Teams:WaitForChild("T1")
    local t2 = game.Teams.T2
    local t3 = game.Teams.T3
    local t4 = game.Teams.T4
    local tu = game.Teams.Undescided
    local player = game.Players.LocalPlayer 
    local plr = player.Character.Humanoid
    plr.Died:Connect(function()
        if player.Team == t1 or player.Team == t2 or player.Team == t3 or player.Team == t4 then
            player.Team = tu                    
        end
    end)
    wait(.5)
end

The error is on line 8 saying " ReplicatedFirst.DeathScript:8: attempt to index field 'Character' (a nil value)" I'm pretty sure that I've used the LocalPlayer.Character before in a local script, but for some reason this one isn't working correctly. I'm sure this is something that I have set up wrong but I would love some help getting it to work. (This is a local script in the ReplicatedFirst folder) Let me know if you need any more information! Thank you!

0
I recommend not putting the code into a loop, as it'll keep on repeatedly setting up the same event over-and-over again. TheeDeathCaster 2368 — 6y

2 answers

Log in to vote
1
Answered by
aazkao 787 Moderation Voter
6 years ago
Edited 6 years ago

Its because your script runs before the character has time to load into the workspace, just use a Wait() method to make sure the character loads before assinging the variable

local plr = game.Players.LocalPlayer.CharacterAdded:Wait()
0
`Players.CharacterAdded` o- o TheeDeathCaster 2368 — 6y
Ad
Log in to vote
0
Answered by 6 years ago

I'd recommend doing this on the server. Staying true to your version, try this.

local Teams = game:GetService('Teams')
local Players = game:GetService('Players')

local Player = Players.LocalPlayer
local Character = Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild('Humanoid')

local Team1 = Teams:WaitForChild('T1')
local Team2 = Teams:WaitForChild('T2')
local Team3 = Teams:WaitForChild('T3')
local Team4 = Teams:WaitForChild('T4')
local Undecided = Teams:WaitForChild('Undescided')

Humanoid.Died:Connect(function()
    if Player.Team ~= Undecided then
        Player.Team = Undecided                    
    end
end)

Answer this question