How to use a value mid-way through a locator?

So, I have a RemoteEvent that is fired from the Client to the Server, and the thing that is fired is a string with a car name. (For an example “Mustang”)

event.OnServerEvent:connect(function(client, car)

I then want to use the value of “car” to locate that car in serverstorage and spawn it. I know that the answer isn’t:

local vehicle =

I know this is just trying to locate “car” from ServerStorage.Cars rather than “Mustang”
How again do you do that though?

1 Like

The simplest solution is:

local vehicle = game.ServerStorage.Cars[car]

However, you might not want to do that because it will error if the car doesn’t exist in ServerStorage. It is probably better to use:

local vehicle = game.ServerStroage.Cars:FindFirstChild(car)
if vehicle then
-- use vehicle variable
-- handle non-existent vehicle (error?)

Use find first child or put brackets like [car]

I’m giving the user a list of cars to chose from, so the only way it’d error is if I mis-spelled something. So it’ll be fine use the former. That being said, thank you a ton. I swear I’m like the best at scripting.

1 Like

Well it’s also smart to consider exploiters. Exploiters can pass your remote whatever data they want so it’s important to make sure that data is valid. A common practice would be:

event.OnServerEvent:connect(function(client, car)
	if typeof(car) == "string" then
		local vehicle = game.ServerStorage.Cars:FindFirstChild(car)
		if vehicle then
			-- do action

This will prevent any bad or unexpected data types (numbers, CFrame, Vector3, etc.) from making your code error.