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

LocalScript in StarterCharacterScripts not working on server?

Asked by
Rhidlor 42
6 years ago

The script below works when testing locally in studio, but fails to work when tested on a server. For the life of me I can't figure out why, I figured I'd ask here because it's probably something small that I overlooked.

sidenote: excuse all the prints, i tried using them to debug to no avail

local replicatedStorage = game:GetService("ReplicatedStorage")
local equipToolEvent = replicatedStorage:FindFirstChild("EquipToolEvent")

local player = game.Players.LocalPlayer
player:WaitForChild("Backpack")
local humanoid = game.Workspace:WaitForChild(player.Name):WaitForChild("Humanoid")
wait(2.5)

function getWeapons()
    local backpack = player.Backpack
    if backpack then
        print("backpack")
        local weapons = {}
        for _, weapon in pairs(backpack:GetChildren()) do
            print("getting " .. weapon.Name)
            table.insert(weapons, weapon)
        end 
        return weapons
    else
        print("!backpack")
    end
end

function getBestWeapon(weapons)
    if weapons then
        print("weapons")
        local bestWeapon
        for _, weapon in pairs(weapons) do
            print(weapon.Name)
            if bestWeapon then
                if weapon.Values.Damage.Value > bestWeapon.Values.Damage.Value then
                    bestWeapon = weapon
                end
            else
                bestWeapon = weapon
            end
        end
        return bestWeapon
    else
        print("!weapons")
    end
end

local weapons = getWeapons()
local bestWeapon = getBestWeapon(weapons)
if bestWeapon then
    equipToolEvent:FireServer(bestWeapon.Name)
else
    print("!bestWeapon")
end

2 answers

Log in to vote
0
Answered by
Jo_Bot 67
6 years ago

Ah, I see what you did I think :P

you have:

local player = game.Players.LocalPlayer

which is typically used in local scripts, but when using StarterCharacterScripts, the scripts and local scripts go inside the character, so I would do this:

local character = script.Parent
local player = game.Players:GetPlayerFromCharacter(character)

the rest of your script looks good, I might have not caught on to a mistake, I don't know. Hopefully I fixed your problem.

Heh, -Jo_Bot

0
Thanks for the answer, I tried your suggestion and although I too thought it made sense it unfortunately didn't seem to solve my problem. Rhidlor 42 — 6y
0
hmm Jo_Bot 67 — 6y
Ad
Log in to vote
0
Answered by
Rhidlor 42
6 years ago

The problem was that I wasn't waiting for the backpack to get filled with tools. So to fix that I added the following code after line 10.

    while #backpack:GetChildren() == 0 do
        wait()
    end

Answer this question