How can I have character models change for each player?

Hello!

I'm VERY new to Photon and Unity, so my code is terrible.

I want a multiplayer game that will be hosting 4 players max. However, I want each player to have an assigned character model—for example, player1=Ninja, player2=Knight, player3=Princess, player4=Viking.

I have made the first players work like this

public class SpawnPlayers : MonoBehaviour

{

  public GameObject playerOne;

  public GameObject playerTwo;

//Random Spawner

  public float minX;

  public float maxX;

  public float minZ;

  public float maxZ;


  private void Start()

  {

// for spawning players

    Vector3 randomPosition = new(Random.Range(minX, maxX), Random.Range(minZ, maxZ));


    if (PhotonNetwork.IsMasterClient)

    {

      PhotonNetwork.Instantiate(playerOne.name, randomPosition, Quaternion.identity);

    }

    else

    {

      PhotonNetwork.Instantiate(playerTwo.name, randomPosition, Quaternion.identity);

    }

  }


}


Is there any way I can make it work for 4 players? I would greatly appreciate it.

Answers

  • You could use Custom Room Properties to store which player uses which character (and "role" in the game). When someone joins, your code can use the PhotonNetwork.CurrentRoom.CustomProperties to iterate over all taken roles. Select one that's not yet in use and try to set the property for it.

    Example: The Custom Room Property "Ninja" defines who is the ninja. Whoever picks this role sets the property to their own PhotonNetwork.LocalPlayer.ActorNumber.

    In an improved implementation you would check if the players who picked a role are all still around (e.g. player 1 was the Ninja but then disconnected). Also, you can use "CAS" to set properties only if nobody else changed them before you (e.g. if multiple players join at the same time and both want to become the Ninja)...

    More in the docs.