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

multiple prefabs for players

Discussion in 'Netcode for GameObjects' started by EctoHanro, Feb 14, 2022.

  1. EctoHanro

    EctoHanro

    Joined:
    Dec 19, 2020
    Posts:
    3
    I think the solution I want is somewhere embedded in here but I cannot work out what to do, and my situation is slightly different.

    I have a 'character' prefab that is set as the PlayerPrefab in the network manager. It's OnNetworkSpawn then instantiates a different prefab as a child object depending on what the player has chosen as the character they want.

    Unfortunately, when 2 players spawn, they both show as the same prefab depending on who you look at. For example, if the druid spawns, and then the knight, the druid will see 2 druids, the knight will see two knights.

    Not sure what to do, please can someone help?
     
  2. CosmoM

    CosmoM

    Joined:
    Oct 31, 2015
    Posts:
    204
    It could be a number of things. Could you post (a trimmed down version of) the relevant code?
     
  3. EctoHanro

    EctoHanro

    Joined:
    Dec 19, 2020
    Posts:
    3
    Sure can! Thank you in advance.

    from the character.cs (the prefab in the PlayerPrefab in the networkmanager):
    Code (CSharp):
    1. public override void OnNetworkSpawn()
    2. {
    3. ...
    4.         base.OnNetworkSpawn();
    5.         string className = _gameManager.className;
    6.         GameObject classPrefab = (GameObject)Resources.Load(className, typeof(GameObject));
    7.         GameObject characterClass = Instantiate(classPrefab, this.transform.position, Quaternion.identity);
    8.  
    9.         characterClass.transform.SetParent(this.transform.Find("Root").gameObject.transform);
    10.  
    11. ...
    12. }
     
  4. CosmoM

    CosmoM

    Joined:
    Oct 31, 2015
    Posts:
    204
    OnNetworkSpawn is called for everyone regardless of ownership. So what is likely happening is that when a new player joins, as OnNetworkSpawn is called for all clients on that object each client therefore retrieves its own className from _gameManager and parents that to their version of the new client's player object. One way to fix this would be to make a function on for example _gameManager that returns the className given a clientId, and in OnNetworkSpawn you then pass in the OwnerId instead of the LocalId.
     
    EctoHanro likes this.
  5. EctoHanro

    EctoHanro

    Joined:
    Dec 19, 2020
    Posts:
    3
    I think I'm going around this the wrong way. I'm going to try and implement a lobby and learn a little bit more about allocating player-specific variables, maybe using connectionData ? Anyhow thank you for your knowledge.
     
    Last edited: Feb 16, 2022