问题描述
我正在尝试建立一个功能,该功能基于不是源自单行为的类来更新玩家的精灵/颜色,但由于这个原因,它不允许我将其添加到光子视图中。
我的游戏有一个名为PlayerDataClass
的类,用于存储本地玩家的所有信息。我尚未将其设置为单一行为类,因为我希望能够在不将其附加到游戏对象的情况下进行访问。但是,由于这个原因,我无法使用photonview访问它。
有没有办法做到这一点?还是有更好的选择?
我目前仅记录ColorTheme
附加的PlayerDataClass
变量的名称,但它仅记录本地客户端变量,而不是调用该函数的客户端。
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
同步到其他客户端。
您的NetworkPlayer
是PlayerDataClass
实例的“所有者”,是一个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并完全发送出去。