【Unet】Unity使用實用Syncvar 簡單同步變數
阿新 • • 發佈:2019-01-29
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class ParticleManager : NetworkBehaviour { [SyncVar(hook = "SetParticleActive")] public bool active = true; public GameObject particle; void Update() { if (Input.GetKeyDown(KeyCode.Q)) { CmdPatricle(!particle.activeInHierarchy); } } [Command] public void CmdPatricle(bool isok) { active = isok; Debug.Log("CMD" + isok); } //bool isok 得到是已經變化後的 active public void SetParticleActive(bool isok) { particle.SetActive(isok); Debug.Log("Hook" + isok); } }
如果上面程式碼 不加 hook
//[SyncVar(hook = "SetParticleActive")] [SyncVar] public bool active = true; public GameObject particle; void Start() { particle = GameObject.Find("Particle System"); } //public override void OnStartClient() //{ // // register client events, enable effects // NetworkServer.SpawnWithClientAuthority(gameObject, connectionToClient); //} void Update() { if (Input.GetKeyDown(KeyCode.Q)) { CmdPatricle(!particle.activeInHierarchy); Debug.Log("End " + active); } } [Command] public void CmdPatricle(bool isok) { active = isok; Debug.Log("CMD" + isok); //因為RPC 在伺服器端呼叫(本地沒有許可權) RpcSetClient(active); } //bool isok 得到是已經變化後的 active public void SetParticleActive(bool isok) { particle.SetActive(isok); Debug.Log("Hook" + isok); } [ClientRpc] public void RpcSetClient(bool isok) { Debug.Log("Client Rpc" + isok); active = isok; particle.SetActive(isok); Debug.Log("Client Rpc active" + active); }
就需要 在加一個 clientRPC