I have a very basic script that teleports players to a specific Vector3 position as seen here:
if player.Character then player.Character:MoveTo(Vector3.new(5,5,5)) end
What I am trying to do, but cannot figure out, is how to have a more generalized Vector3 value so that the position will change based on which map is loaded and where the part "Spawn" is in that map. My attempt at the solution:
Maps = game.ReplicatedStorage.Maps:GetChildren() --Gets the map Spawn = Maps.Spawn.Value.Value --Vector3Value parented to a part called "Spawn" if player.Character then player.Character:MoveTo(Vector3.new(Spawn)) --Attempt to use the Vector3 value end
I get an error as a result of running the code above which says "attempt to index field 'Spawn' (a nil value). Is there something I am doing wrong?
So what is happening is GetChildren is a table of indexes and values. Hence there is that i,v in pairs
often times used. Since GetChildren's indexes are all number values from 1 to however many objects are children under the object. The script is seeing something like:
{ 1 = Brick, 2 = Brick, 3 = Brick, 4 = Spawn, --etc. }
Since the index values are numbers and doing Maps.Spawn
, the Spawn is the index the script is trying to find. However, since Spawn can never be an index for GetChildren, it will return a nil value.
The best way I see to do this is just using FindFirstChild on the Maps model to find Spawn. This may be a temporary fix, however you would need to ask with further attempt of making this script separate spawns for teams.
Maps = game.ReplicatedStorage.Maps:GetChildren() --Gets the map Spawn = Maps:FindFirstChild("Spawn") SpawnVector = Spawn.Value.Value --Vector3Value parented to a part called "Spawn" if player.Character then player.Character:MoveTo(SpawnVector) --Since you claim Spawn (Now SpawnVector) was a Vector3Value object, having Vector3.new() is redundant. end
You called GetChildren() on Maps, GetChildren returns a table whereas I expect you want a random map from that folder? Here's a quick fix that would get a random map from the maps
Maps=game.ReplicatedStorage.Maps:GetChildren()[math.random(1,#game.ReplicatedStorage.Maps:GetChildren())]