Hi all,
I’m jumping into the world of networking with unity, using UNET. I’m putting together a simple project but I’ve ran into a problem with syncing movement.
Previously, I used the Network Transform that unity provides, which is generally okay but a bit stuttery. So I looked into options with fixing this and found many threads relating to using NetworkView and OnSerializeNetworkView with lerping to smooth out movement.
I put together a quick solution, but before I show you that, I should note:
-
I’m using the basic unity provided Network Manager to auto spawn my player.
-
I have appropriately dragged the NetworkListener script to be the observed portion within the NetworkView, both of which are attached to my player object prefab.
The following is my code for the NetworkListener script that manages this :
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class NetworkListener : MonoBehaviour {
public Vector3 realPosition = Vector3.zero;
public Quaternion realRotation;
public Vector3 sendPosition = Vector3.zero;
public Quaternion sendRotation;
public NetworkView nView;
void Start()
{
nView = GetComponent<NetworkView>();
}
void OnSerializeNetworkView (BitStream stream, NetworkMessageInfo info)
{
Debug.Log ("OnSerializeNetworkView was called");
if (stream.isWriting)
{
Debug.Log ("I'm writing this stream.");
sendPosition = this.transform.position;
sendRotation = this.transform.rotation;
stream.Serialize (ref sendPosition);
stream.Serialize (ref sendRotation);
}
else if (stream.isReading)
{
Debug.Log ("I'm reading this stream.");
stream.Serialize (ref realPosition);
stream.Serialize (ref realRotation);
}
}
void Update()
{
if (nView.isMine == false)
{
Debug.Log ("This NV isn't yours - from NetworkListener");
transform.position = Vector3.Lerp (this.transform.position, realPosition, Time.deltaTime * 15);
transform.rotation = Quaternion.Lerp (this.transform.rotation, realRotation, Time.deltaTime * 30);
}
}
}
Unfortunately, it doesn’t sync anything. In addition, OnSerializeNetworkView is not being called because it’s not outputting the debug line which you can see there. I’ve put debug lines throughout to help me find out where anything could be going wrong.
Does anyone have any ideas? Is it because I’m using Unity’s basic Network Manager to auto spawn my player?