Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

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,062
    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,462
    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