UNET single player (offline) mode

Hi all,

I’m converting my game from single to multi-player mode.

I have followed all the basic steps to use UNET:

  • create NetworkManager + HUD

  • change player script from MonoBehaviour to NetworkBehaviour

  • assign player prefab NetworkIdentity + NetworkTransform

I’m spawning my Player prefab manually on Start() of my Game script. After that the player instance is in the scene, but disabled.

I know after that I need to call NetworkServer.Spawn(instantiatedPlayer);, but I get this error:

NetworkServer is not active. Cannot spawn objects without an active server.

My question is: can we Instantiate players without server being active? Something like offline mode, where NetworkBehaviour does not disable my objects.

Maybe I should start server manually from script on Awake() even in the SinglePlayer game? Is starting server synchronous, so I can instantiate and call NetworkServer.Spawn right after starting it?

Having separate online/offline scenes and player prefabs is not very convenient.

Best!

In multi-player mode, you need to Start Host, register the prefabs on the client, instantiate your players, then networkserver.spawn the players (so they are created on clients).

AFAIK you need an active network before calling networkserver.spawn because you can’t spawn client player prefabs on clients if the clients haven’t started yet.

I am struggling with the same problem. Have you found any solution yet?

Hi, yes,

offline/single-player mode is just Host on local.

In your Start() function of your game script, make a simple local Host.

After host is made, OnClientConnect on your NetworkManager will be called. I’m using custom network manager (that inherits from NetworkManager).

// Called on the client when connected to a server.
public override void OnClientConnect(NetworkConnection conn)
{
    ClientScene.Ready(conn);
    ClientScene.AddPlayer(0);
}

After that, the OnServerAddPlayer will be called. In it you have to Instantiate your player.

public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
{
    GameObject player = Instantiate(yourPlayer);
    player.transform.position = yourInitialPosition;

    NetworkServer.AddPlayerForConnection(conn, player , playerControllerId);
}

And you will have your player in the scene.

1 Like