如何通过光子统一网络发送同步脚本

本文关键字:同步 脚本 网络 何通过 | 更新日期: 2023-09-27 18:19:43

我有一个多人游戏,它使用手电筒,如果我按下L,另一个游戏的手电筒也会关闭,但当batteryTimeLeft达到20时,它只在本地游戏上闪烁。

我如何将整个脚本与所有用户同步,以便闪烁也能通过网络传播?

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class LightManager : Photon.MonoBehaviour {
    public GameObject flashlight;
    public Light lightinflashlight;
    public bool Lightenabled = true;
    public float batteryTimeLeft = 100f;
    public float batteryDrainRate;
    public float minIntensity = 0.25f;
    public float maxIntensity = 8f;
    public bool flashlightRanOut = false;
    float random;
    float noise;
    public float time=3;
    void start(){
        PhotonView photonView = this.photonView;
        lightinflashlight = GetComponentInChildren<Light> ();
    }
    void Update () {
        photonView.RPC("publicUpdate", PhotonTargets.All); 
    }
    void FixedUpdate() {
        photonView.RPC("publicFixedUpdate", PhotonTargets.All); 
    }
    [PunRPC]
    public void publicFixedUpdate(){
        batteryTimeLeft -= batteryDrainRate;
        if (time < 0) {
            time = 0;
        } 
        time--;
    }
    [PunRPC]
    public void publicUpdate(){
        if (batteryTimeLeft >= 20) {
            flashlight.GetComponent<Light> ().intensity = 8;
            flashlightRanOut = false;
        }
        if (batteryTimeLeft < 0) {
            batteryTimeLeft = 0;
            flashlightRanOut=true;
        }
        if (!flashlightRanOut) {
            if (batteryTimeLeft <= 20) {
                if (time > 1) {
                    random = Random.Range (0.0f, 150.0f);
                    noise = Mathf.PerlinNoise (random, Time.time);
                    flashlight.GetComponent<Light> ().intensity = Mathf.Lerp (minIntensity, maxIntensity, noise);
                }
            }
            if (time < 0) {
                time = 3;
            }
            if (Input.GetKeyDown (KeyCode.L)) {
                Lightenabled = ! Lightenabled;
            }
            flashlight.SetActive (Lightenabled);
        } else {
            flashlight.SetActive (false);
        }
    }
}

如何通过光子统一网络发送同步脚本

最优化的网络解决方案是同步数据良好且传输数据量最少的解决方案,只要在手电筒打开或关闭时通过网络发送即可,并在两个客户端上创建计时器,因此两个客户端上将独立生成flashlightRanOut,两个客户端也将生成噪音,闪烁会有所不同,因为它使用随机值,但不需要完全相同的闪烁(也不可能做到这一点,因为延迟会把它搞砸)。