How do I make an object spawn from serverstorage when a textbutton is clicked on the gui?
For example, a car that is named car1. I want the object to spawn in front of a brick a certain place not in front of the player.
You need to take into consideration about Filtering Enabled and some Basic Events.
Filtering enabled does not let the client directly communicate with things on the server. If you were to clone something from a client(the player or in other terms a local script), the only person that would see the clone would be the player.
Client can not see the ServerStorage, so we would neeed to use a remote event.
There are a few ways that the client can communicate with the server and vice-versa. You may have heard of something called “Remote Event” sometime when you were trying to insert an instance. Try inserting a remote event into ReplicatedStorage. Name it to “CarEvent”. Let’s insert a script into ServerScriptService. Let’s call that script “CarServer”. We are going to write a few lines of code in this script.
First, we need to start off by setting a variable for ReplicatedStorage.
local repStorage = game.ReplicatedStorage
Next, we are going to set a variable for the RemoteEvent we made.
local event = repStorage.CarEvent
So, we have two lines of code so far. Next, we are going to use something called an event. This will make the code run when something happens. You will learn a little more about events if you scroll down.
Let’s use the event, OnServerEvent from the RemoteEvent. Remember there is argument that always get passed on this event. It is there Player, no matter you include it or not.
Inside of there, you would want to clone your car.
Events are basically like something that waits until a certain condition is met. There are many events in the Roblox API, some you may have already used. Let’s use an event for a TextButton. Inside of a text button, insert a local script. Let’s name this “ClientCar” We are going to use the event that runs when a player clicked the text button.
First off, let’s create our variables for ReplicatedStorage and our CarEvent in ReplicatedStorage. We did this before in the filtering enabled topic.
We are going to make the event now.
This event will only run when the script’s parent or in other words the text button gets clicked. Now we can fire the server to call our event on the server.
script.Parent.MouseButton1Click:Connect(function() event:FireServer() end
The server will know that we fired it and the script we made inside of ServerScriptService will run when we click this. We don’t need to do anything for this text button.
I don’t have time to get the car spawning for you to work, but basically you would clone the car in the OnServerEvent of the server script. You would use the method :SetPrimaryPartCFrame() of the model to correctly position it.
I hope you understand this.