I have a very basic script that teleports players to a specific Vector3 position as seen here:
1 | if player.Character then |
2 | player.Character:MoveTo(Vector 3. new( 5 , 5 , 5 )) |
3 | 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:
1 | Maps = game.ReplicatedStorage.Maps:GetChildren() --Gets the map |
2 | Spawn = Maps.Spawn.Value.Value --Vector3Value parented to a part called "Spawn" |
3 |
4 | if player.Character then |
5 | player.Character:MoveTo(Vector 3. new(Spawn)) --Attempt to use the Vector3 value |
6 | 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 | { |
2 | 1 = Brick, |
3 | 2 = Brick, |
4 | 3 = Brick, |
5 | 4 = Spawn, |
6 | --etc. |
7 | } |
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.
1 | Maps = game.ReplicatedStorage.Maps:GetChildren() --Gets the map |
2 | Spawn = Maps:FindFirstChild( "Spawn" ) |
3 | SpawnVector = Spawn.Value.Value --Vector3Value parented to a part called "Spawn" |
4 |
5 | if player.Character then |
6 | player.Character:MoveTo(SpawnVector) --Since you claim Spawn (Now SpawnVector) was a Vector3Value object, having Vector3.new() is redundant. |
7 | 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
1 | Maps = game.ReplicatedStorage.Maps:GetChildren() [ math.random( 1 ,#game.ReplicatedStorage.Maps:GetChildren()) ] |