每个人都有自己的知识体系。
Toggle navigation
Home
随笔
C#/.Net
树莓派 / Raspberry
皓月汉化组
Beego
Golang
OxideMod
apache
haproxy
windows
Java
Objective-C
日语/罗马音歌词/日语常识
MongoDB
python
电学
公告
Minecraft服务器-公告
NanoPi
C4D (CINEMA 4D)
生活
推流/m3u8/rtmp/rtsp
Unity3d
ffmpeg
数据结构
区块链
tarui
UnityForPSVita
About Me
Archives
Tags
Unity Mirror 基础机制SyncVar
2022-05-17 16:05:14
805
0
0
akiragatsu
***一,用SyncVar进行同步*** 函数标签[SyncVar] 用标签来标记变量,被改变时时,同步给其他客户端; 可指定Hook指定回调函数,并返回旧值和新值 如: [SyncVar(hook = nameof(ChangeColor))] Color pcolor = Color.white; void ChangeColor(Color oldc, Color newc) { } 即pcolor发生变化时,客户端都调用ChangeColor PS:使用此特性标注的变量,只应该在服务器上对此变量进行更改,而通过hook在客户端作用此更改 然后hook,仅会再客户端调用。如果服务器是OnlyServer模式则不会调用 使用脚本让服务器控制所有客户端颜色变化的代码 using UnityEngine; using Mirror; public class PlayerController : NetworkBehaviour { [SyncVar(hook = nameof(ChangeColor))] Color pcolor = Color.white; Rigidbody rb; MaterialPropertyBlock prop; /// <summary> /// 客户端收到同步时调用 /// </summary> /// <param name="oldc"></param> /// <param name="newc"></param> void ChangeColor(Color oldc, Color newc) { Debug.Log("更新为新颜色"); prop.SetColor("_Color", newc); GetComponent<Renderer>().SetPropertyBlock(prop); } private void Awake() { rb = GetComponent<Rigidbody>(); prop = new MaterialPropertyBlock(); GetComponent<Renderer>().GetPropertyBlock(prop); } float duringTimer = 0f; private void Update() { rb.velocity = new Vector3(0, 0, 0); //仅服务器改变它 if (isServer) { if (duringTimer < 2f) { duringTimer += Time.deltaTime; } else { duringTimer = 0f; pcolor = pcolor == Color.white ? Color.black : Color.white; } } } } 效果: ![title](/api/file/getImage?fileId=62835e0fbbb3220ae400a1bf) 作为客户端被通知到时的堆栈 ![title](/api/file/getImage?fileId=62835e8abbb3220ae400a1c0)
Pre:
Unity Mirrot 基础机制:Command,ClientRpc,TargetRpc
Next:
Unity Mirrio 基础构建方式(两种)
0
likes
805
Weibo
Wechat
Tencent Weibo
QQ Zone
RenRen
Submit
Sign in
to leave a comment.
No Leanote account?
Sign up now.
0
comments
More...
Table of content
No Leanote account? Sign up now.