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

How can i Spawn a Model when Press a Key?

Asked by 2 years ago

im making a script that spawn a Throne in front of me when i press B, i made a LocalScript to get the key B, it fire an Event that's inside the LocalScript and then a ServerScript get on by the Event, it is inside the event

LocalScript:

local Players = game:GetService("Players") 
local Player = Players.LocalPlayer 
local Character = Player.Character or Player.CharacterAdded:Wait()


game:GetService("UserInputService").InputBegan:Connect(function(Input, GameProcessed)
    if (GameProcessed) then return end 
    if Input.KeyCode == Enum.KeyCode.B then 
        script.SpawnThroneEvent:FireServer()
        print("Local Script Throne Spawn")
    end
end)

ServerScript:

local bool = 0
--local throne = game.ReplicatedStorage:WaitForChild("BaragganThroneRemote")

local players = game:GetService("Players")
local player = players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local hrp = character:WaitForChild("HumanoidRootPart")

local rs = game:GetService("ReplicatedStorage")
local ThroneTest = rs:WaitForChild("ThroneTest")
local model = ThroneTest:Clone()


script.Parent.OnServerEvent:Connect(function(Player)
    if Player then
        if bool == 0 then
                bool = 1
        elseif bool == 1 then
            bool = 0
        end
    end
    -----------------------------------
    while bool == 1 do
        model.Parent = game.Workspace
        model:PivotTo(hrp.CFrame * CFrame.new(-10, 4, 0))
    end
    while bool== 0 do
        game:GetService("Workspace"):WaitForChild("ThroneTest"):Destroy()
    end
end)

LocalScript is working, but the rest no, wt im doing wrong?

1 answer

Log in to vote
0
Answered by 2 years ago

Because you cannot get players.LocalPlayer in a server script, so you should do something like this for the server script:

local spawnThroneEvent = [insert path to RemoteEvent]
local throneModel = [insert path to throne model]
local throneExists = false

spawnThroneEvent.OnServerEvent:Connect(function(player)
    local character = player.Character
    if not character then return end

    if throneExists then
        workspace[throneModel.Name]:Destroy()
    else
        local clone = throneModel:Clone
        clone.Parent = workspace
        clone:PivotTo(character.HumanoidRootPart.CFrame * CFrame.new(-10, 4, 0))
    end

    throneExists = not throneExists --this changes the bool, if the current bool is true, it makes it false, if the current bool is false, it makes it true, better than using 0 and 1 as bool
end)
Ad

Answer this question