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

How can I make a script that chooses a random character?

Asked by 1 year ago

I am attempting to make code that will change your avatar to a random premade avatar when you join, or if your user id matches will give you a specific avatar, without using StarterCharecter. Ive been going around trying to get help for a while but nothing is helping. This code isn't finished as I've been super stumped (I'm a amateur ). All responses are appreciated.

local allStarterCharacter = {workspace.StarterCharacter1,workspace.StarterCharacter2,workspace.StarterCharacter3.StarterCharacterSP} -- You put all your playermodels in a table using {}
local pick = math.random(1,#allStarterCharacter ) -- By adding # behind a table, it gives you the amount of values it has (3 in this case)
local clone = allStarterCharacter[pick]:Clone()
local Players = game:GetService("Players")

Players.PlayerAdded:Wait()

for i, v in pairs(Players:GetPlayers()) do
    if v.UserId == 847431372 then
        pick then clone
    else

    end
end

1 answer

Log in to vote
0
Answered by 1 year ago

I recommend putting the StarterCharacters in ReplicatedStorage instead of Workspace.

Make a normal script in StarterCharacterScripts and paste this:

local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

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

local StarterCharacters = { -- assuming you already moved the StarterCharacters in ReplicatedStorage
    ReplicatedStorage.StarterCharacter1,
    ReplicatedStorage.StarterCharacter2,
    ReplicatedStorage.StarterCharacter3.StarterCharacterSP
}

local pick = Random.new(os.time()):NextInteger(1, #StarterCharacters) -- math.random() but more accurately random

if player.UserId == 847431372 then
    pick = 3 -- let's say StarterCharacter3.StarterCharacterSP is the specific avatar
end

local chosen = StarterCharacters[pick]
local clone = chosen:Clone()

clone.HumanoidRootPart.CFrame = character.HumanoidRootPart.CFrame -- places the clone to the position of the player

clone.Parent = workspace -- puts in workspace

for _, limb in ipairs(clone:GetDescendants()) do
    if limb:IsA("BasePart") -- if it's a limb of the clone
        limb:SetNetworkOwner(player) -- making the clone connected to the player's internet
    end
end

player.Character = clone -- sets the player's character to the clone, letting the player have control of the clone

character:Destroy() -- deletes the old avatar and stops this script

The reason why we put this in StarterCharacterScript is that whenever the player spawns/respawns, everything inside that will be moved to the player's character and will run once moved to the player's character.

Ad

Answer this question