How to spawn players in spawn positions without overlapping?

Hello, I am trying to spawn players in the spawn positions, when my game starts the game manager instantiates the players, how can I assign the firs player to first spawn position the second to the second spawn position and so on?

in my game up to 4 players can join, and I have 4 spawn positions.

it can be played as 2 , 3 or 4 players

I tried to use this code but it doesn't work...

------------------------------------------------

public GameObject playerPrefab;

public Transform[] spawnPositions;


private void Start()

   {

     PhotonNetwork.Instantiate(playerPrefab.name, transform.position, Quaternion.identity, 0);

     AssignPlayerPositions();

   }


   void AssignPlayerPositions()

   {

     GameObject[] objs = GameObject.FindGameObjectsWithTag("Player");


     if (objs.Length == 1)

     {

        objs[0].transform.position = spawnPositions[0].position;

     }

     if (objs.Length == 2)

     {

        objs[0].transform.position = spawnPositions[0].position;

        objs[1].transform.position = spawnPositions[1].position;

     }

     if (objs.Length == 3)

     {

        objs[0].transform.position = spawnPositions[0].position;

        objs[1].transform.position = spawnPositions[1].position;

        objs[2].transform.position = spawnPositions[2].position;

     }

     if (objs.Length == 4)

     {

        objs[0].transform.position = spawnPositions[0].position;

        objs[1].transform.position = spawnPositions[1].position;

        objs[2].transform.position = spawnPositions[2].position;

        objs[3].transform.position = spawnPositions[3].position;

     }

   }

Answers

  • Have a look at OnJoinedInstantiate.cs. It has a list of spawn points and could be a blueprint for your case.

  • ty for your reply, i tried to use the OnJoinedInstantiate.cs on my game manager, i added the prefab and spawn locations, but when the game started it didn't spawned the player... can u tell me how can i use this script?

  • when the game started it didn't spawned the player

    It doesn't spawn players when the game starts. You have to connect, join a room and then it will spawn the players. This should be automatic, provided the script is in the scene and enabled, when the client actually joins the room (OnJoinedRoom() happens once and if the component is not live and registered to get callbacks, then it will miss this moment)...

    Also make sure you don't spawn the objects, then load another scene (which usually destroys existing objects).