访问 none Monobehaviour class 查看 Photonview

Accessing none Monobehaviour class view Photonview

我正在尝试设置一个函数来根据 class 更新玩家 sprites/colours,该 class 不是从单一行为派生的,但正因为如此,它不允许我添加它到光子视图。

我的游戏有一个名为 PlayerDataClass 的 class,用于存储本地玩家的所有信息。我没有将其设置为单一行为 class,因为我希望能够在不将其附加到游戏对象的情况下访问它。但是正因为如此,我无法使用 photonview 访问它。

有办法吗?或者有更好的选择吗?

我目前只记录附加到 PlayerDataClassColorTheme 变量的名称,但它只记录本地客户端变量而不是调用该函数的客户端。

PlayerDataClass.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using Photon.Pun;

[Serializable]
public class PlayerDataClass
{
    [SerializeField] private string username;
    [SerializeField] private string colorTheme;
    [SerializeField] private string color1;
    [SerializeField] private string color2;

    public string Username {
        get { return username; }
        set {
            username = value;
            PhotonNetwork.NickName = value;
        }
    }

    public string ColorTheme {
        get { return colorTheme; }
        set { colorTheme = value; }
    }

    public string Color1 {
        get { return color1; }
        set { color1 = value; }
    }

    public string Color2 {
        get { return color2; }
        set { color2 = value; }
    }
}

NetworkPlayer.cs

using Photon.Pun;
using Photon.Realtime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class NetworkPlayer : MonoBehaviourPun
{
    public Vector3 m_NetworkPosition = Vector3.zero;
    Rigidbody2D rb;
    public PlayerDataClass m_Player = new PlayerDataClass();

    void Awake()
    {
        // Import scripts
    }

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();

        if (!photonView.IsMine)
        {
            photonView.RPC("UpdateColor", RpcTarget.AllBuffered, null);
        }
    }

    [PunRPC]
    void UpdateColor()
    {
        Debug.Log("local color name is " + m_Player.ColorTheme);
    }
}

听起来您想要的是将 m_Player.ColorTheme 同步到其他客户端。

您的 NetworkPlayerPlayerDataClass 实例 的“所有者” MonoBehaviourPun 因此您可以中继所有需要的同步调用通过它 .. 就像你基本上已经对 UpdateColor 所做的一样......你只需要传入一个参数:

[PunRPC]
void UpdateColor(string theme)
{
    // Assign the received string
    m_Player.ColorTheme = theme;
    Debug.Log($"local color name is now \"{m_Player.ColorTheme}\"");
}

并这样称呼它

// instead you should rather do this only if you ARE the owner of this view
// YOU want to tell OTHER users what your color is
if (photonView.IsMine)
{
    // Pass in the string to be synced 
    // Rather use OthersBuffered since you don't want to receive
    // your own call again
    photonView.RPC(nameof(UpdateColor), RpcTarget.OthersBuffered, m_Player.ColorTheme);
}

你也可以考虑把你的整个PlayerDataClass一个光子同步Custom Type然后完全发送过来。