1.概述
在多人游戏场景中,场景内的交互对象会和不同玩家之间发生交互,这个时候需要解决场景内状态同步的问题,比如和野怪、道具等之间的交互,为了解决这一问题,我使用了untiy的netcode来解决。
2.将下面脚本挂载到你需要状态同步的对象上即可,脚本代码如下
public class GameObjectSync : NetworkBehaviour
{
// Start is called before the first frame update
NetworkVariable<Vector3> _syncPos = new NetworkVariable<Vector3>() ;
NetworkVariable<Quaternion> _syncRot = new NetworkVariable<Quaternion>();
Transform _syncTransform;
private void Start()
{
_syncTransform = transform;
}
bool isCanUpdate;
// Update is called once per frame
void Update()
{
UploadTransform();
}
private void FixedUpdate()
{
if(isCanUpdate) SyncTransform();
}
private void SyncTransform()
{
//_syncTransform.position = _syncPos.Value;
//_syncTransform.rotation = _syncRot.Value;
_syncTransform.position = Vector3.Lerp(_syncTransform.position, _syncPos.Value, Time.deltaTime * 10f);
_syncTransform.rotation = Quaternion.Lerp(_syncTransform.rotation, _syncRot.Value, Time.deltaTime * 10f);
}
//上传位置
private void UploadTransform()
{
if (IsServer)
{
_syncPos.Value = _syncTransform.position;
_syncRot.Value = _syncTransform.rotation;
}
else
{
UploadTransformServerRpc(_syncTransform.position, _syncTransform.rotation);
}
isCanUpdate = true;
}
[ServerRpc(RequireOwnership = false)]
private void UploadTransformServerRpc(Vector3 position, Quaternion rotation)
{
_syncPos.Value = position;
_syncRot.Value = rotation;
}
}
这里使用了NetworkVariable做游戏对象状态同步,注意游戏对象还要挂载netcode的游戏对象脚本。
- 网络同步变量的用法
修改变量(必须服务端执行修改操作)
读取变量