【问题标题】:How to get other player's value in Unity when I use Mirror Network?使用镜像网络时如何在 Unity 中获取其他玩家的价值?
【发布时间】:2022-09-23 11:05:32
【问题描述】:

你好?我现在正在学习 MIRROR 网络。

enter image description here

但是,我在获取其他玩家的价值方面存在问题。这张图片解释了我想要做什么。

enter image description here

我创建了 3 个项目。一个是服务器(本地主机),另一个是客户端 A,另一个是客户端 B。

首先,我写了这样的代码:

public class PlayerManager : NetworkBehaviour
{
    [SyncVar(hook = nameof(onValueChanged))]
    int value = 0;

    private void Update()
    {
        if(isServer && Input.GetKeyDown(\"x\"))
        {
            Message();
        }
    }

    public override void OnStartServer()
    {
        Debug.Log(\"Here is Game Room Scene, Player add Successfully\");
    }

    [Command] 
    private void Hola()
    {
        value++;   

        Debug.Log(\"Received Hola from the client!\");
        Debug.Log(\"Server Value : \" + value);
        ReplyHola();
    }

    [TargetRpc]
    private void ReplyHola()
    {
        Debug.Log(\"Received Hola from Client!\");
    }

    [ClientRpc]
    private void Message()
    {
        Debug.Log(\"Ping...\");
    }

    [ClientRpc]
    private void UpdateValue(int value)
    {
        this.value = value;
    }

    private void onValueChanged(int oldValue, int newValue)
    {
        Debug.Log(\"New Value Detective :\");
        Debug.Log(\"Old Value : \" + oldValue);
        Debug.Log(\"New Value : \" + newValue);
        Debug.Log(\"Sum Value : \" + PlayerStat.Value);
    }
}

3 个项目具有所有相同的代码。我引用了这个视频中的代码(https://www.youtube.com/watch?v=8tKFF0RP9Jw)。

而且,我编写了关于总和客户端 A 和 B 的代码,如下所示:

private void SumDatas()
{
    foreach(var playerObj in FindObjectsOfType(typeof(GameObject)) as GameObject[])
    {
        if(gameObject.name == \"Player(Clone)\")
        {
            PlayerStat.Value += GameObject.Find(\"Player(Clone)\").transform.GetComponent<PlayerManager>().GetValue();
        }
    }
}

PlayerStat 是一个静态类,代码如下:

public static class PlayerStat
{
    public static int Value { get; set; }
}

有人帮我吗?

    标签: unity3d mirror


    【解决方案1】:

    我解决了这个问题。对于与我有同样问题的其他人,我不会删除此问题。

    我在我的服务器项目、客户端 A 和 B 项目中添加了这段代码:

     [SyncVar(hook = nameof(onValueChanged))]
     int value = 0;
    
     int myValue = 0;
    
     private void Update()
     {
        myValue = PlayerStat.Value;   
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-29
      • 2022-01-14
      • 2020-10-18
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多