Hey!
I’m working on a simple proof-of-concept application with network functionalities.
The idea is to create a server, where multiple clients can connect. Every time a server (or host) is started, a 3D game object, e.g. a Sphere, is spawned, thus, there is always only one game object in a one-to-many (server to client) relation. For now, only the server should be able to move the object, and clients should only see the object transforming.
For the network functionalities I’m using the built-in Network Manager with a custom network manager class. In the spawn info
of my Network Manager I have a Sphere prefab that has a Rigidbody
, Network Identity
, Network Transform
, and a script component attached.
In my custom network manager class I have the following to handle that only the server can spawn a sphere object. Not sure if conn.hostId==-1
is the correct way, but couldn’t find another way to check if the current connecting player is creating a server or just joining as a client.
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
class CustomNetworkManager : NetworkManager
{
public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
{
if (conn.hostId == -1) {
GameObject player = (GameObject)Instantiate (playerPrefab, Vector3.zero, Quaternion.identity);
NetworkServer.AddPlayerForConnection (conn, player, playerControllerId);
}
}
}
The code for the sphere is quite simple:
using UnityEngine;
using UnityEngine.Networking;
public class SphereController : NetworkBehaviour {
// Update is called once per frame
void Update () {
var x = Input.GetAxis("Horizontal")*0.1f;
var z = Input.GetAxis("Vertical")*0.1f;
transform.Translate(x, 0, z);
}
}
The sphere is spawned correctly if I start a LAN as host. I can also connect as a client just fine, and also see the sphere. Right now I can move the sphere in both applications (server and client), since I don’t have any conditionals in my SphereController
class.
How do I pass the transformation info from my server to my client? I thought the Network Transform
component would take care of that, but I guess I somehow need to pass the information in the SphereController
?