如何在Unity中通过网络发送Texture2D?

时间:2018-08-20 14:57:10

标签: c# unity3d texture2d photon

因此,我有一个游戏,玩家必须依靠Texture2D进行游戏,我需要将Texture2D发送给其他玩家,但是onPhotonSerializeView并不能解决这个问题,因为Exception: cannot serialize(): UnityEngine.Texture2D

我在网站上找到了this solution,但我不太了解,所以也许有人可以帮忙。

我的代码:

private Texture2D DrawingSection;

private void Awake()
{
    DrawingSection = GameObject.Find("Canvas/pan_Background/pan_DrawingSection").GetComponent<Texture2D>();
}

private void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
    if (stream.isWriting)
    {
        if (photonView.isMine)
        {
           stream.SendNext(DrawingSection);
        }
    }
    else
    {
        DrawingSection = (Texture2D)stream.ReceiveNext();
    }
}

1 个答案:

答案 0 :(得分:0)

由于您无法发送Texture2D,因此需要将其转换为byte[]

var bytes = DrawingSection.EncodeToPNG();

然后发送类似

的字节
stream.SendNext(bytes);

读取字节时,您会收到一个byte[]

var bytes = (byte[])stream.ReceiveNext();

然后,您需要将byte[]解析为Texture2D

这可能应该可行,我假设双方的TextureFormat和大小相同?

DrawingSection.LoadImage(bytes);