Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Any way to stop players spawning in the same place?

Discussion in 'Multiplayer' started by zigglr, Oct 21, 2015.

  1. zigglr

    zigglr

    Joined:
    Sep 28, 2015
    Posts:
    82
    I have this to spawn the player at one of three spawn locations (there will be 3 players), but how do I stop players spawning in the same spot?

    public void OnJoinedRoom()
    {
    if (PhotonNetwork.playerList.Length == 1)
    {
    Debug.Log("2 Players In Room Starting Level");

    number = UnityEngine.Random.Range(1, 3);


    if (number == 1)
    {
    spawnpoint = GameObject.FindWithTag("spawnpoint1");
    }


    if (number == 2)
    {
    spawnpoint = GameObject.FindWithTag("spawnpoint2");
    }

    if (number == 3)
    {
    spawnpoint = GameObject.FindWithTag("spawnpoint2");
    }
    }


    GameObject myPlayer = PhotonNetwork.Instantiate(playerprefabname, spawnpoint.transform.position, spawnpoint.transform.rotation, 0);

    Thanks
     
  2. tobiass

    tobiass

    Joined:
    Apr 7, 2009
    Posts:
    3,086
    The code looks kind of OK.
    Some tips: Range() for integers exclude the max value you set, so you only get numbers 1 and 2. You likely have a copy&paste error in the number 3 case (spawnpoint2).
    And I would not use 3 tags but one "SpawnPoints". You can find them as list of objects and pick a random point from those.
     
  3. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,647
    Something like this?

    Code (csharp):
    1.  
    2.         public void PlayerSpawn()
    3.         {
    4.             GameObject[] spawnPoints = GameObject.FindGameObjectsWithTag("SpawnPoint");
    5.             GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
    6.             const float minSafeDistance = 2;
    7.  
    8.             GameObject safeSpawnPoint =
    9.                 (from spawn in spawnPoints from player in players
    10.                  where Vector3.Distance(spawn.transform.position, player.transform.position) > minSafeDistance
    11.                  select spawn).FirstOrDefault();
    12.  
    13.             GameObject myPlayer = Instantiate(Player);
    14.         }
     
    Last edited: Oct 22, 2015