I’m using Mirror Networking for my game and am on the stage of creating the players, doing it manually because I need individual setup. Problem is when I spawn the actual player object, it doesn’t replicate to a new client, not even its own player object. What the player object does when it spawns is (from the server) it spawns another object for their character. Those DO spawn on the client and replicate their position and everything just fine, but they don’t have the assigned name given to them on instantiation.
NetworkManager
public override void OnClientConnect()
{
base.OnClientConnect();
CreatePlayerMessage plrMessage = new CreatePlayerMessage {
Username = "Guest " + UnityEngine.Random.Range(1, 10000).ToString().PadLeft(4, '0')
};
NetworkClient.Send(plrMessage);
}
public override void OnStartServer() {
base.OnStartServer();
NetworkServer.RegisterHandler<CreatePlayerMessage>(OnCreatePlayerObject);
}
void OnCreatePlayerObject(NetworkConnectionToClient conn, CreatePlayerMessage message) {
// playerPrefab is the one assigned in the inspector in Network
// Manager but you can use different prefabs per race for example
GameObject gameobject = Instantiate(playerPrefab);
// Apply data from the message however appropriate for your game
// Typically Player would be a component you write with syncvars or properties
Player player = gameobject.GetComponent<Player>();
player.username = message.Username;
gameobject.name = $"{message.Username} [connId={conn.connectionId}]";
gameobject.transform.parent = GameObject.Find("PlayersService").transform;
// call this to use this gameobject as the primary controller
NetworkServer.AddPlayerForConnection(conn, gameobject);
}
public struct CreatePlayerMessage : NetworkMessage {
public string Username;
}
Player
public class Player : NetworkBehaviour
{
[SyncVar]
public string username;
[SerializeField] private GameObject PlayerCharacterPrefab;
public GameObject Character;
public CameraMode CameraMode = CameraMode.Classic;
public override void OnStartServer() {
Debug.Log($"Hello from {username}!");
if (Game.Players.AutoLoadCharacters) {
LoadCharacter();
}
}
[Server]
public void LoadCharacter() {
if (PlayerCharacterPrefab == null) {
Debug.LogError("PlayerCharacterPrefab is not set!");
return;
}
Character = Instantiate(PlayerCharacterPrefab);
Character.GetComponent<PlayerController>().Init(this, 100f,
CameraMode == CameraMode.Classic ? Character.transform.Find("RP") :
Character.GetComponent<PlayerController>().PlayerModel().Find("Char").Find("Root").Find("Torso").Find("Head").Find("CameraAttachment"));
Character.name = username;
NetworkServer.Spawn(Character, connectionToClient);
}
}