如何在 Unity 中将 canvas 与 Photon Engine 同步

How to synchronized a canvas with Photon Engine in Unity

我正在尝试将 canvas 与光子引擎同步,以便每个玩家都能看到它。 canvas 就像一台电视,任何玩家都可以打开,其他人可以观看。我可以同步一个立方体,将 PhotonView 和 PhotonRigidBody 组件添加到预制件中,但是当我尝试使用 canvas 进行相同操作时,它根本不起作用。 谁能告诉我执行此操作需要哪些组件,如果需要它我应该用额外的脚本处理什么(即转让所有权)。

canvas没有什么特别的地方,但是可以锁住

我有两种解决方案:

Observable Component:

您可以编写自定义可观察组件,并将其添加到 PhotonView:

To make use of this function, the script has to implement the IPunObservable interface.

public class CustomObservable : MonoBehaviourPunCallbacks, IPunObservable
{
    [SerializeField] PlayerController playerController;

    public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.IsWriting)
        {
            stream.SendNext(playerController.playerNumber);
            stream.SendNext(playerController.playerScore);
        }
        else
        {
            playerController.playerNumber = (int)stream.ReceiveNext();
            playerController.playerScore = (float)stream.ReceiveNext();
        }
    }
}

Custom Properties:

您还可以使用自定义属性在所有玩家之间同步数据。

Photon's Custom Properties consist of a key-values Hashtable which you can fill on demand. The values are synced and cached on the clients, so you don't have to fetch them before use. Changes are pushed to the others by SetCustomProperties().

How is this useful? Typically, rooms and players have some attributes that are not related to a GameObject: The current map or the color of a player's character (think: 2d jump and run). Those can be sent via Object Synchronization or RPC, but it is often more convenient to use Custom Properties.

PhotonNetwork.CurrentRoom.SetCustomProperties(Hashtable propsToSet)

您可以编写一个使用 Photons 回调的脚本,并更新 UI 个元素。

OnRoomPropertiesUpdate(Hashtable propertiesThatChanged)