unity游戏开发之场景内道具状态同步

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的游戏对象脚本。

  • 网络同步变量的用法

修改变量(必须服务端执行修改操作)

读取变量

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值