Spawning Players Manually
Tutorial for creating a script to manually spawn your players when you call a method.
2
4
Create a SpawnPlayers method
public void SpawnPlayers()
{
if (_playerPrefab == null)
{
Debug.LogWarning("Player prefab is not assigned and thus cannot be spawned.");
return;
}
foreach (NetworkConnection client in ServerManager.Clients.Values)
{
// Since the ServerManager.Clients collection contains all clients (even non-authenticated ones),
// we need to check if they are authenticated first before spawning a player object for them.
if (!client.IsAuthenticated)
continue;
NetworkObject obj = Instantiate(_playerPrefab);
Spawn(obj, client, gameObject.scene);
}
}6
7
Handle starting scenes
// If the client isn't observing this scene, make him an observer of it.
if (!client.Scenes.Contains(gameObject.scene))
SceneManager.AddConnectionToScene(client, gameObject.scene);// If the client isn't in this scene, ignore him.
if (!client.Scenes.Contains(gameObject.scene))
continue;8
The final script
using FishNet.Connection;
using FishNet.Managing;
using FishNet.Object;
using UnityEngine;
public class ManualPlayerSpawner : NetworkBehaviour
{
[SerializeField] private NetworkObject _playerPrefab;
// The Server attribute here prevents this method from being called except on the server.
[Server]
public void SpawnPlayers()
{
if (_playerPrefab == null)
{
Debug.LogWarning("Player prefab is not assigned and thus cannot be spawned.");
return;
}
foreach (NetworkConnection client in ServerManager.Clients.Values)
{
// Since the ServerManager.Clients collection contains all clients (even non-authenticated ones),
// we need to check if they are authenticated first before spawning a player object for them.
if (!client.IsAuthenticated)
continue;
// If the client isn't observing this scene, make him an observer of it.
if (!client.Scenes.Contains(gameObject.scene))
SceneManager.AddConnectionToScene(client, gameObject.scene);
NetworkObject obj = NetworkManager.GetPooledInstantiated(_playerPrefab, asServer: true);
Spawn(obj, client, gameObject.scene);
}
}
}Last updated